<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}

include '../config/db.php';

$message = '';
$error = '';

// Get cancellation request ID from URL
$request_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Handle approval/rejection
if ($request_id && $action) {
    $status = ($action == 'approve') ? 'approved' : 'rejected';
    
    // Get request details before updating
    $request_query = $conn->query("
        SELECT cr.*, u.name, u.email, u.mobile 
        FROM cancellation_requests cr 
        JOIN users u ON cr.user_id = u.id 
        WHERE cr.id = $request_id
    ");
    
    if ($request_query->num_rows > 0) {
        $request = $request_query->fetch_assoc();
        
        // Update cancellation request status
        $update_query = "UPDATE cancellation_requests SET status = '$status' WHERE id = $request_id";
        
        if ($conn->query($update_query)) {
            // If approved, update user's membership status
            if ($action == 'approve') {
                $conn->query("UPDATE users SET membership_active = 0 WHERE id = {$request['user_id']}");
                $message = "Membership cancellation request has been approved. User's membership is now inactive.";
            } else {
                $message = "Membership cancellation request has been rejected. User's membership remains active.";
            }
            
            // You can add email notification here
            // mail($request['email'], "Membership Cancellation Update", $message);
            
            header("refresh:2;url=dashboard.php");
        } else {
            $error = "Error updating request status: " . $conn->error;
        }
    } else {
        $error = "Cancellation request not found.";
    }
}

// Get cancellation request details for display
$request_query = $conn->query("
    SELECT cr.*, u.name, u.email, u.mobile, u.address, u.kyc_status, u.membership_active, u.total_donation 
    FROM cancellation_requests cr 
    JOIN users u ON cr.user_id = u.id 
    WHERE cr.id = $request_id
");

if ($request_query->num_rows == 0) {
    header("Location: dashboard.php");
    exit();
}

$request = $request_query->fetch_assoc();
$request_date = new DateTime($request['requested_at']);
$now = new DateTime();
$days_pending = $request_date->diff($now)->days;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Process Cancellation Request - Admin Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        /* Header */
        .header {
            background: white;
            border-radius: 20px;
            padding: 1.5rem 2rem;
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .header h1 {
            font-size: 1.8rem;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .header h1 i {
            color: #dc3545;
        }

        .back-btn {
            background: #6c757d;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            text-decoration: none;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .back-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        /* Main Content Grid */
        .content-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 2rem;
        }

        @media (max-width: 768px) {
            .content-grid {
                grid-template-columns: 1fr;
            }
            body {
                padding: 1rem;
            }
        }

        /* Card Style */
        .card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            animation: slideIn 0.5s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .card-header {
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            color: white;
            padding: 1.5rem;
        }

        .card-header.warning {
            background: linear-gradient(135deg, #dc3545, #c82333);
        }

        .card-header h2 {
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-body {
            padding: 1.5rem;
        }

        /* Detail Rows */
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 1rem 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: 600;
            color: #666;
        }

        .detail-value {
            color: #333;
            font-weight: 500;
        }

        /* Status Badges */
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .status-pending {
            background: #ffc107;
            color: #856404;
        }

        .status-approved {
            background: #28a745;
            color: white;
        }

        .status-rejected {
            background: #dc3545;
            color: white;
        }

        .status-active {
            background: #28a745;
            color: white;
        }

        .status-inactive {
            background: #dc3545;
            color: white;
        }

        /* Reason Box */
        .reason-box {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 10px;
            margin: 1rem 0;
            border-left: 4px solid #dc3545;
        }

        .reason-box p {
            color: #333;
            line-height: 1.6;
            margin-top: 0.5rem;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .btn {
            flex: 1;
            padding: 1rem;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            text-align: center;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn-approve {
            background: linear-gradient(135deg, #28a745, #218838);
            color: white;
        }

        .btn-approve:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40,167,69,0.3);
        }

        .btn-reject {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            color: white;
        }

        .btn-reject:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(108,117,125,0.3);
        }

        /* Message Alerts */
        .alert {
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideIn 0.3s ease-out;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border-left: 4px solid #17a2b8;
        }

        /* Timeline */
        .timeline {
            margin-top: 1rem;
        }

        .timeline-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.75rem 0;
            border-left: 2px solid #e0e0e0;
            margin-left: 1rem;
            padding-left: 2rem;
            position: relative;
        }

        .timeline-item::before {
            content: '';
            position: absolute;
            left: -8px;
            top: 50%;
            width: 14px;
            height: 14px;
            border-radius: 50%;
            background: #2c5f2d;
        }

        .timeline-date {
            font-weight: 600;
            color: #2c5f2d;
            min-width: 100px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-top: 1rem;
        }

        .stat-box {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 10px;
            text-align: center;
        }

        .stat-box i {
            font-size: 2rem;
            color: #2c5f2d;
            margin-bottom: 0.5rem;
        }

        .stat-box .stat-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #333;
        }

        .stat-box .stat-label {
            font-size: 0.85rem;
            color: #666;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background: white;
            border-radius: 20px;
            max-width: 500px;
            width: 90%;
            padding: 2rem;
            text-align: center;
        }

        .modal-content i {
            font-size: 4rem;
            margin-bottom: 1rem;
        }

        .modal-buttons {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        /* Loading Spinner */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Notes Section */
        .notes-section {
            margin-top: 1rem;
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 10px;
        }

        .notes-section textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-family: 'Poppins', sans-serif;
            resize: vertical;
            margin-top: 0.5rem;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <div class="header">
        <h1>
            <i class="fas fa-user-times"></i>
            Process Cancellation Request
        </h1>
        <a href="dashboard.php" class="back-btn">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>

    <!-- Messages -->
    <?php if($message): ?>
    <div class="alert alert-success">
        <i class="fas fa-check-circle"></i>
        <span><?= htmlspecialchars($message) ?></span>
    </div>
    <?php endif; ?>

    <?php if($error): ?>
    <div class="alert alert-error">
        <i class="fas fa-exclamation-circle"></i>
        <span><?= htmlspecialchars($error) ?></span>
    </div>
    <?php endif; ?>

    <div class="content-grid">
        <!-- Request Details Card -->
        <div class="card">
            <div class="card-header warning">
                <h2>
                    <i class="fas fa-file-alt"></i>
                    Cancellation Request Details
                </h2>
            </div>
            <div class="card-body">
                <div class="detail-row">
                    <span class="detail-label">Request ID:</span>
                    <span class="detail-value">#<?= str_pad($request['id'], 6, '0', STR_PAD_LEFT) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Request Date:</span>
                    <span class="detail-value"><?= date('d M Y, h:i A', strtotime($request['requested_at'])) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Days Pending:</span>
                    <span class="detail-value">
                        <?= $days_pending ?> day(s)
                        <?php if($days_pending > 7): ?>
                            <span style="color: #dc3545;"> (Urgent)</span>
                        <?php endif; ?>
                    </span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Current Status:</span>
                    <span class="detail-value">
                        <span class="status-badge status-<?= $request['status'] ?>">
                            <i class="fas fa-<?= $request['status'] == 'pending' ? 'clock' : ($request['status'] == 'approved' ? 'check-circle' : 'times-circle') ?>"></i>
                            <?= ucfirst($request['status']) ?>
                        </span>
                    </span>
                </div>

                <!-- Reason for Cancellation -->
                <div class="reason-box">
                    <strong><i class="fas fa-comment"></i> Reason for Cancellation:</strong>
                    <p><?= nl2br(htmlspecialchars($request['reason'])) ?></p>
                </div>
            </div>
        </div>

        <!-- Member Details Card -->
        <div class="card">
            <div class="card-header">
                <h2>
                    <i class="fas fa-user"></i>
                    Member Information
                </h2>
            </div>
            <div class="card-body">
                <div class="detail-row">
                    <span class="detail-label">Member ID:</span>
                    <span class="detail-value">#<?= str_pad($request['user_id'], 6, '0', STR_PAD_LEFT) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Full Name:</span>
                    <span class="detail-value"><?= htmlspecialchars($request['name']) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Email Address:</span>
                    <span class="detail-value"><?= htmlspecialchars($request['email']) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Mobile Number:</span>
                    <span class="detail-value"><?= $request['mobile'] ?: 'Not provided' ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Address:</span>
                    <span class="detail-value"><?= $request['address'] ?: 'Not provided' ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">KYC Status:</span>
                    <span class="detail-value">
                        <span class="status-badge status-<?= $request['kyc_status'] ?>">
                            <?= ucfirst($request['kyc_status']) ?>
                        </span>
                    </span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Membership Status:</span>
                    <span class="detail-value">
                        <span class="status-badge status-<?= $request['membership_active'] ? 'active' : 'inactive' ?>">
                            <?= $request['membership_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Total Donation:</span>
                    <span class="detail-value" style="color: #28a745; font-weight: bold;">
                        ₹<?= number_format($request['total_donation'], 2) ?>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- Member Statistics Card -->
    <div class="card" style="margin-top: 2rem;">
        <div class="card-header">
            <h2>
                <i class="fas fa-chart-line"></i>
                Member Statistics
            </h2>
        </div>
        <div class="card-body">
            <div class="stats-grid">
                <?php
                // Get member's donation history
                $donation_stats = $conn->query("
                    SELECT 
                        COUNT(*) as total_donations,
                        SUM(amount) as total_amount,
                        MAX(amount) as max_donation,
                        MIN(amount) as min_donation
                    FROM donations 
                    WHERE user_id = {$request['user_id']} AND status = 'verified'
                ")->fetch_assoc();
                
                // Get member's membership duration
                $member_since = $conn->query("SELECT created_at FROM users WHERE id = {$request['user_id']}")->fetch_assoc();
                $member_since_date = new DateTime($member_since['created_at']);
                $membership_duration = $member_since_date->diff($now);
                ?>
                <div class="stat-box">
                    <i class="fas fa-calendar-alt"></i>
                    <div class="stat-value"><?= $membership_duration->y ?> years</div>
                    <div class="stat-label">Membership Duration</div>
                </div>
                <div class="stat-box">
                    <i class="fas fa-donate"></i>
                    <div class="stat-value"><?= $donation_stats['total_donations'] ?? 0 ?></div>
                    <div class="stat-label">Total Donations</div>
                </div>
                <div class="stat-box">
                    <i class="fas fa-chart-simple"></i>
                    <div class="stat-value">₹<?= number_format($donation_stats['total_amount'] ?? 0, 0) ?></div>
                    <div class="stat-label">Lifetime Contribution</div>
                </div>
                <div class="stat-box">
                    <i class="fas fa-trophy"></i>
                    <div class="stat-value">₹<?= number_format($donation_stats['max_donation'] ?? 0, 0) ?></div>
                    <div class="stat-label">Highest Donation</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Request Timeline Card -->
    <div class="card" style="margin-top: 2rem;">
        <div class="card-header">
            <h2>
                <i class="fas fa-history"></i>
                Request Timeline
            </h2>
        </div>
        <div class="card-body">
            <div class="timeline">
                <div class="timeline-item">
                    <div class="timeline-date"><?= date('d M Y', strtotime($request['requested_at'])) ?></div>
                    <div>Cancellation request submitted by member</div>
                </div>
                <?php if($request['status'] != 'pending'): ?>
                <div class="timeline-item">
                    <div class="timeline-date"><?= date('d M Y') ?></div>
                    <div>Request <?= $request['status'] ?> by Admin</div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Action Buttons (Only if pending) -->
    <?php if($request['status'] == 'pending'): ?>
    <div class="card" style="margin-top: 2rem;">
        <div class="card-header warning">
            <h2>
                <i class="fas fa-gavel"></i>
                Take Action
            </h2>
        </div>
        <div class="card-body">
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i>
                <span>Please review the cancellation request carefully before making a decision. Once approved, the member's membership will be deactivated immediately.</span>
            </div>

            <div class="action-buttons">
                <button class="btn btn-reject" onclick="showConfirmModal('reject')">
                    <i class="fas fa-times-circle"></i> Reject Request
                </button>
                <button class="btn btn-approve" onclick="showConfirmModal('approve')">
                    <i class="fas fa-check-circle"></i> Approve Cancellation
                </button>
            </div>

            <!-- Admin Notes -->
            <div class="notes-section">
                <label style="font-weight: 600;">
                    <i class="fas fa-sticky-note"></i> Admin Notes (Optional)
                </label>
                <textarea id="adminNotes" rows="3" placeholder="Add any internal notes about this cancellation request..."></textarea>
            </div>
        </div>
    </div>
    <?php elseif($request['status'] == 'approved'): ?>
    <div class="card" style="margin-top: 2rem;">
        <div class="card-body" style="text-align: center;">
            <i class="fas fa-check-circle" style="font-size: 4rem; color: #28a745;"></i>
            <h3 style="color: #155724; margin-top: 1rem;">Request Already Processed</h3>
            <p>This cancellation request has already been approved. The member's membership is now inactive.</p>
        </div>
    </div>
    <?php elseif($request['status'] == 'rejected'): ?>
    <div class="card" style="margin-top: 2rem;">
        <div class="card-body" style="text-align: center;">
            <i class="fas fa-times-circle" style="font-size: 4rem; color: #dc3545;"></i>
            <h3 style="color: #721c24; margin-top: 1rem;">Request Rejected</h3>
            <p>This cancellation request has been rejected. The member's membership remains active.</p>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Confirmation Modal -->
<div id="confirmModal" class="modal">
    <div class="modal-content">
        <i id="modalIcon" class="fas fa-question-circle" style="color: #ffc107;"></i>
        <h3 id="modalTitle">Confirm Action</h3>
        <p id="modalMessage">Are you sure you want to perform this action?</p>
        <div class="modal-buttons">
            <button class="btn-reject" style="flex:1;" onclick="closeModal()">
                <i class="fas fa-times"></i> Cancel
            </button>
            <button class="btn-approve" style="flex:1;" id="confirmBtn">
                <i class="fas fa-check"></i> Confirm
            </button>
        </div>
    </div>
</div>

<script>
    let currentAction = '';
    let confirmUrl = '';

    function showConfirmModal(action) {
        currentAction = action;
        const modal = document.getElementById('confirmModal');
        const modalIcon = document.getElementById('modalIcon');
        const modalTitle = document.getElementById('modalTitle');
        const modalMessage = document.getElementById('modalMessage');
        const confirmBtn = document.getElementById('confirmBtn');
        
        if (action === 'approve') {
            modalIcon.className = 'fas fa-user-slash';
            modalIcon.style.color = '#dc3545';
            modalTitle.innerHTML = 'Approve Cancellation';
            modalMessage.innerHTML = 'Are you sure you want to APPROVE this cancellation request? This will deactivate the member\'s membership immediately and they will lose all member benefits.';
            confirmBtn.innerHTML = '<i class="fas fa-check"></i> Yes, Approve Cancellation';
            confirmBtn.className = 'btn-approve';
            confirmUrl = '?id=<?= $request_id ?>&action=approve';
        } else {
            modalIcon.className = 'fas fa-user-check';
            modalIcon.style.color = '#28a745';
            modalTitle.innerHTML = 'Reject Cancellation';
            modalMessage.innerHTML = 'Are you sure you want to REJECT this cancellation request? The member will retain their active membership and all benefits.';
            confirmBtn.innerHTML = '<i class="fas fa-check"></i> Yes, Reject Request';
            confirmBtn.className = 'btn-reject';
            confirmUrl = '?id=<?= $request_id ?>&action=reject';
        }
        
        modal.style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('confirmModal').style.display = 'none';
    }

    function submitAction() {
        if (confirmUrl) {
            // Save admin notes if any
            const adminNotes = document.getElementById('adminNotes')?.value || '';
            if (adminNotes) {
                // You can store notes in session or database if needed
                console.log('Admin notes:', adminNotes);
                // Optional: Save to database
                // fetch('save_admin_notes.php', { method: 'POST', body: JSON.stringify({request_id: <?= $request_id ?>, notes: adminNotes}) });
            }
            window.location.href = confirmUrl;
        }
    }

    // Set confirm button action
    document.getElementById('confirmBtn').onclick = function() {
        submitAction();
    };

    // Close modal when clicking outside
    window.onclick = function(event) {
        const modal = document.getElementById('confirmModal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }

    // Keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
        }
    });
</script>
</body>
</html>