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

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

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

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

// Handle approval/rejection
if ($payment_id && $action) {
    $status = ($action == 'approve') ? 'verified' : 'rejected';
    
    // Update payment status
    $update_query = "UPDATE donations SET status = '$status' WHERE id = $payment_id";
    if ($conn->query($update_query)) {
        // If approved, update user's total donation
        if ($status == 'verified') {
            // Get donation amount and user_id
            $donation_query = $conn->query("SELECT user_id, amount FROM donations WHERE id = $payment_id");
            $donation = $donation_query->fetch_assoc();
            
            // Update user's total donation
            $conn->query("UPDATE users SET total_donation = total_donation + {$donation['amount']} WHERE id = {$donation['user_id']}");
        }
        
        $message = "Payment has been " . ($status == 'verified' ? "verified successfully!" : "rejected!");
        header("refresh:2;url=dashboard.php");
    } else {
        $error = "Error updating payment status: " . $conn->error;
    }
}

// Get payment details
$payment_query = $conn->query("
    SELECT d.*, u.name, u.email, u.mobile, u.kyc_status 
    FROM donations d 
    JOIN users u ON d.user_id = u.id 
    WHERE d.id = $payment_id
");

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

$payment = $payment_query->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Payment - 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: 1200px;
            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: #2c5f2d;
        }

        .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 */
        .content-grid {
            display: grid;
            grid-template-columns: 1fr 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 h2 {
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-header h2 i {
            font-size: 1.5rem;
        }

        .card-body {
            padding: 1.5rem;
        }

        /* Payment Details */
        .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-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-verified {
            background: #28a745;
            color: white;
        }

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

        /* Payment Proof Image */
        .proof-image {
            text-align: center;
            margin: 1rem 0;
        }

        .proof-image img {
            max-width: 100%;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            cursor: pointer;
            transition: transform 0.3s;
        }

        .proof-image img:hover {
            transform: scale(1.02);
        }

        /* 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, #dc3545, #c82333);
            color: white;
        }

        .btn-reject:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(220,53,69,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;
        }

        /* 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-content h3 {
            margin-bottom: 1rem;
        }

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

        /* Lightbox for Image */
        .lightbox {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            justify-content: center;
            align-items: center;
            z-index: 2000;
            cursor: pointer;
        }

        .lightbox img {
            max-width: 90%;
            max-height: 90%;
            border-radius: 10px;
        }

        /* 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: 1.5rem;
            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-credit-card"></i>
            Verify Payment
        </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; ?>

    <!-- Main Content -->
    <div class="content-grid">
        <!-- Payment Details Card -->
        <div class="card">
            <div class="card-header">
                <h2>
                    <i class="fas fa-info-circle"></i>
                    Payment Information
                </h2>
            </div>
            <div class="card-body">
                <div class="detail-row">
                    <span class="detail-label">Transaction ID:</span>
                    <span class="detail-value">#<?= str_pad($payment['id'], 6, '0', STR_PAD_LEFT) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Amount:</span>
                    <span class="detail-value" style="color: #28a745; font-size: 1.3rem;">
                        ₹<?= number_format($payment['amount'], 2) ?>
                    </span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Payment Date:</span>
                    <span class="detail-value"><?= date('d M Y, h:i A', strtotime($payment['uploaded_at'])) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Current Status:</span>
                    <span class="detail-value">
                        <span class="status-badge status-<?= $payment['status'] ?>">
                            <i class="fas fa-<?= $payment['status'] == 'pending' ? 'clock' : ($payment['status'] == 'verified' ? 'check-circle' : 'times-circle') ?>"></i>
                            <?= ucfirst($payment['status']) ?>
                        </span>
                    </span>
                </div>
            </div>
        </div>

        <!-- Donor Details Card -->
        <div class="card">
            <div class="card-header">
                <h2>
                    <i class="fas fa-user"></i>
                    Donor Information
                </h2>
            </div>
            <div class="card-body">
                <div class="detail-row">
                    <span class="detail-label">Name:</span>
                    <span class="detail-value"><?= htmlspecialchars($payment['name']) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Email:</span>
                    <span class="detail-value"><?= htmlspecialchars($payment['email']) ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Mobile:</span>
                    <span class="detail-value"><?= $payment['mobile'] ?: 'Not provided' ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">KYC Status:</span>
                    <span class="detail-value">
                        <span class="status-badge status-<?= $payment['kyc_status'] ?>">
                            <?= ucfirst($payment['kyc_status']) ?>
                        </span>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Proof Card -->
    <div class="card" style="margin-top: 2rem;">
        <div class="card-header">
            <h2>
                <i class="fas fa-image"></i>
                Payment Proof / Screenshot
            </h2>
        </div>
        <div class="card-body">
            <div class="proof-image">
                <?php if($payment['payment_proof'] && file_exists("../" . $payment['payment_proof'])): ?>
                    <img src="../<?= $payment['payment_proof'] ?>" alt="Payment Proof" onclick="openLightbox(this.src)" style="max-width: 100%; border-radius: 10px;">
                    <p style="margin-top: 0.5rem; color: #666;">
                        <i class="fas fa-search-plus"></i> Click image to zoom
                    </p>
                <?php else: ?>
                    <div style="background: #f8f9fa; padding: 3rem; text-align: center; border-radius: 10px;">
                        <i class="fas fa-image" style="font-size: 4rem; color: #ccc;"></i>
                        <p style="margin-top: 1rem; color: #999;">No payment proof uploaded</p>
                    </div>
                <?php endif; ?>
            </div>

            <?php if($payment['status'] == 'pending'): ?>
            <div class="action-buttons">
                <button class="btn btn-approve" onclick="showConfirmModal('approve')">
                    <i class="fas fa-check-circle"></i> Approve Payment
                </button>
                <button class="btn btn-reject" onclick="showConfirmModal('reject')">
                    <i class="fas fa-times-circle"></i> Reject Payment
                </button>
            </div>

            <!-- Notes for Admin -->
            <div class="notes-section">
                <label style="font-weight: 600;">
                    <i class="fas fa-sticky-note"></i> Admin Notes (Optional)
                </label>
                <textarea rows="3" id="adminNotes" placeholder="Add any notes about this payment verification..."></textarea>
            </div>
            <?php elseif($payment['status'] == 'verified'): ?>
            <div style="text-align: center; padding: 2rem; background: #d4edda; border-radius: 10px;">
                <i class="fas fa-check-circle" style="font-size: 3rem; color: #28a745;"></i>
                <h3 style="color: #155724; margin-top: 0.5rem;">Payment Already Verified</h3>
                <p>This payment has already been approved and added to the total fund.</p>
            </div>
            <?php else: ?>
            <div style="text-align: center; padding: 2rem; background: #f8d7da; border-radius: 10px;">
                <i class="fas fa-times-circle" style="font-size: 3rem; color: #dc3545;"></i>
                <h3 style="color: #721c24; margin-top: 0.5rem;">Payment Rejected</h3>
                <p>This payment has been rejected. The donor may need to resubmit.</p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Verification Guidelines Card -->
    <div class="card" style="margin-top: 2rem;">
        <div class="card-header">
            <h2>
                <i class="fas fa-clipboard-list"></i>
                Verification Guidelines
            </h2>
        </div>
        <div class="card-body">
            <ul style="list-style: none;">
                <li style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                    Check if the payment screenshot is clear and readable
                </li>
                <li style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                    Verify the amount matches the donation amount
                </li>
                <li style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                    Confirm the transaction ID is valid
                </li>
                <li style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                    Check if the payment date is recent
                </li>
                <li style="margin-bottom: 0.75rem; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-check-circle" style="color: #28a745;"></i>
                    Ensure donor has submitted proper KYC if required
                </li>
            </ul>
        </div>
    </div>
</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>

<!-- Lightbox Modal -->
<div id="lightbox" class="lightbox" onclick="closeLightbox()">
    <img id="lightboxImg" src="">
</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-check-circle';
            modalIcon.style.color = '#28a745';
            modalTitle.innerHTML = 'Approve Payment';
            modalMessage.innerHTML = 'Are you sure you want to approve this payment? This will add the amount to the total fund and update the donor\'s contribution.';
            confirmBtn.innerHTML = '<i class="fas fa-check"></i> Yes, Approve';
            confirmBtn.className = 'btn-approve';
            confirmUrl = '?id=<?= $payment_id ?>&action=approve';
        } else {
            modalIcon.className = 'fas fa-times-circle';
            modalIcon.style.color = '#dc3545';
            modalTitle.innerHTML = 'Reject Payment';
            modalMessage.innerHTML = 'Are you sure you want to reject this payment? The donor will be notified and may need to resubmit.';
            confirmBtn.innerHTML = '<i class="fas fa-times"></i> Yes, Reject';
            confirmBtn.className = 'btn-reject';
            confirmUrl = '?id=<?= $payment_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);
            }
            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';
        }
    }

    // Lightbox functions
    function openLightbox(src) {
        const lightbox = document.getElementById('lightbox');
        const lightboxImg = document.getElementById('lightboxImg');
        lightboxImg.src = src;
        lightbox.style.display = 'flex';
    }

    function closeLightbox() {
        document.getElementById('lightbox').style.display = 'none';
    }

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