<?php
include '../includes/auth.php';
include '../config/db.php';
$user_id = $_SESSION['user_id'];

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $amount = $_POST['amount'];
    
    // Validate amount
    if($amount <= 0) {
        $error_message = "Please enter a valid amount greater than 0.";
    } elseif(!isset($_FILES['proof']) || $_FILES['proof']['error'] == UPLOAD_ERR_NO_FILE) {
        $error_message = "Please upload payment screenshot.";
    } else {
        // Create directory if not exists
        $upload_dir = "../assets/uploads/payment_proof/";
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_name = time() . "_" . basename($_FILES['proof']['name']);
        $target = $upload_dir . $file_name;
        $file_type = strtolower(pathinfo($target, PATHINFO_EXTENSION));
        
        // Validate file type - Added 'jfif' to allowed types
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'jfif'];
        
        // Also check MIME type for jfif files
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $_FILES['proof']['tmp_name']);
        finfo_close($finfo);
        
        $allowed_mime_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'application/pdf', 'image/jfif', 'image/jpe'];
        
        if(in_array($file_type, $allowed_types) || in_array($mime_type, $allowed_mime_types)) {
            if(move_uploaded_file($_FILES['proof']['tmp_name'], $target)) {
                $stmt = $conn->prepare("INSERT INTO donations (user_id, amount, payment_proof, status) VALUES (?, ?, ?, 'pending')");
                $stmt->bind_param("ids", $user_id, $amount, $target);
                if($stmt->execute()) {
                    $success_message = "✓ Payment proof uploaded successfully! Awaiting admin verification.";
                } else {
                    $error_message = "Database error. Please try again.";
                }
            } else {
                $error_message = "Failed to upload file. Please try again.";
            }
        } else {
            $error_message = "Invalid file type. Allowed: JPG, JPEG, PNG, GIF, JFIF, PDF";
        }
    }
}

// Get user's recent donations
$recent_donations = $conn->query("SELECT * FROM donations WHERE user_id=$user_id ORDER BY uploaded_at DESC LIMIT 5");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Make a Donation - Gau Seva Foundation</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;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

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

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

        .back-btn:hover {
            background: #1a3a1a;
            transform: translateX(-5px);
        }

        /* Main Grid */
        .main-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
        }

        /* Cards */
        .card {
            background: white;
            border-radius: 20px;
            padding: 2rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-title {
            font-size: 1.5rem;
            color: #2c5f2d;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #eee;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        /* QR Section */
        .qr-section {
            text-align: center;
        }

        .qr-code {
            background: white;
            padding: 2rem;
            border-radius: 20px;
            display: inline-block;
            margin: 1rem 0;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .qr-code img {
            width: 250px;
            height: 250px;
            object-fit: contain;
        }

        .payment-details {
            background: #f5f5f5;
            padding: 1rem;
            border-radius: 10px;
            margin: 1rem 0;
            text-align: left;
        }

        .payment-details p {
            margin: 0.5rem 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .payment-details i {
            color: #2c5f2d;
            width: 25px;
        }

        /* Form Styles */
        .form-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
            font-weight: 500;
        }

        label i {
            color: #2c5f2d;
            margin-right: 8px;
        }

        input[type="number"],
        input[type="file"] {
            width: 100%;
            padding: 0.8rem 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
            font-family: 'Poppins', sans-serif;
        }

        input[type="number"]:focus,
        input[type="file"]:focus {
            outline: none;
            border-color: #2c5f2d;
            box-shadow: 0 0 0 3px rgba(44, 95, 45, 0.1);
        }

        input[type="number"] {
            background: #f9f9f9;
        }

        .file-input-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }

        .file-input-wrapper input[type="file"] {
            padding: 0.8rem;
            cursor: pointer;
        }

        .btn-submit {
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            color: white;
            width: 100%;
            padding: 1rem;
            border: none;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(44, 95, 45, 0.3);
        }

        /* Alert Messages */
        .alert {
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideDown 0.5s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

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

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

        /* Recent Donations Table */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        th {
            background: #f5f5f5;
            color: #2c5f2d;
            font-weight: 600;
        }

        .status-badge {
            display: inline-block;
            padding: 0.3rem 0.8rem;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-verified {
            background: #d4edda;
            color: #155724;
        }

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

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        /* Suggested Amounts */
        .suggested-amounts {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            margin-top: 1rem;
        }

        .amount-btn {
            background: #f5f5f5;
            border: 2px solid #e0e0e0;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }

        .amount-btn:hover {
            background: #2c5f2d;
            color: white;
            border-color: #2c5f2d;
        }

        /* Responsive */
        @media (max-width: 968px) {
            .main-grid {
                grid-template-columns: 1fr;
            }

            body {
                padding: 1rem;
            }

            .qr-code img {
                width: 200px;
                height: 200px;
            }
        }

        @media (max-width: 480px) {
            .header h1 {
                font-size: 1.3rem;
            }

            .card-title {
                font-size: 1.3rem;
            }

            th, td {
                padding: 0.5rem;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>
                <i class="fas fa-hand-holding-heart"></i>
                Make a Donation
            </h1>
            <a href="dashboard.php" class="back-btn">
                <i class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
        </div>

        <div class="main-grid">
            <!-- Left Column - QR & Payment Info -->
            <div class="card">
                <div class="card-title">
                    <i class="fas fa-qrcode"></i>
                    Scan & Pay
                </div>
                
                <div class="qr-section">
                    <div class="qr-code">
                        <img src="https://bmyouth.org/sheldang/assets/qr/qr.jpeg" alt="Scan to Pay">
                    </div>
                    
                    <!-- <div class="payment-details">
                        <p><i class="fas fa-university"></i> <strong>Bank:</strong> Punjab National Bank</p>
                        <p><i class="fas fa-user"></i> <strong>Account Name:</strong> MAHAMILAN YUVA FARMER PRODUCER COMPANY LIMITED</p>
                        <p><i class="fas fa-credit-card"></i> <strong>Account No:</strong> 0601202100000550</p>
                        <p><i class="fas fa-code-branch"></i> <strong>IFSC Code:</strong> PUNB0060120</p>
                        <p><i class="fas fa-mobile-alt"></i> <strong>UPI ID:</strong> -</p>
                    </div>
                    -->
                    <p style="color: #666; font-size: 0.9rem; margin-top: 1rem;">
                        <i class="fas fa-info-circle"></i> 
                        Scan QR code or use UPI ID to make payment, then upload screenshot below
                    </p>
                </div>
            </div>

            <!-- Right Column - Upload Form -->
            <div class="card">
                <div class="card-title">
                    <i class="fas fa-upload"></i>
                    Upload Payment Proof
                </div>

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

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

                <form method="POST" enctype="multipart/form-data" id="donationForm">
                    <div class="form-group">
                        <label><i class="fas fa-rupee-sign"></i> Donation Amount (₹)</label>
                        <input type="number" step="0.01" name="amount" id="amount" required placeholder="Enter amount in INR">
                        
                        
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-image"></i> Please upload Payment Proof Screenshot</label>
                        <div class="file-input-wrapper">
                            <input type="file" name="proof" id="proof" accept="image/*,application/pdf" required>
                        </div>
                        <small style="color: #666; display: block; margin-top: 0.5rem;">
                            <i class="fas fa-info-circle"></i> 
                            Allowed formats: JPG, JPEG, PNG, GIF, JFIF, PDF (Max 5MB)
                        </small>
                    </div>

                    <button type="submit" class="btn-submit">
                        <i class="fas fa-paper-plane"></i>
                        Submit Payment Proof
                    </button>
                </form>

                <div style="margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #eee;">
                    <p style="color: #666; font-size: 0.85rem; text-align: center;">
                        <i class="fas fa-clock"></i> 
                        After verification, your donation will be reflected within 24-48 hours
                    </p>
                </div>
            </div>
        </div>

        <!-- Recent Donations History -->
        <div class="card" style="margin-top: 2rem;">
            <div class="card-title">
                <i class="fas fa-history"></i>
                Your Donation History
            </div>
            
            <div class="table-container">
                </table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Amount (₹)</th>
                            <th>Status</th>
                            <th>Transaction ID</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($recent_donations && $recent_donations->num_rows > 0): ?>
                            <?php while($donation = $recent_donations->fetch_assoc()): ?>
                            <tr>
                                <td><?= date('d M Y, h:i A', strtotime($donation['uploaded_at'])) ?></td>
                                <td><strong>₹<?= number_format($donation['amount'], 2) ?></strong></td>
                                <td>
                                    <span class="status-badge status-<?= $donation['status'] ?>">
                                        <?php if($donation['status'] == 'verified'): ?>
                                            <i class="fas fa-check-circle"></i> Verified
                                        <?php elseif($donation['status'] == 'pending'): ?>
                                            <i class="fas fa-clock"></i> Pending
                                        <?php else: ?>
                                            <i class="fas fa-times-circle"></i> Rejected
                                        <?php endif; ?>
                                    </span>
                                </td>
                                <td><small>#DON-<?= str_pad($donation['id'], 6, '0', STR_PAD_LEFT) ?></small></td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; padding: 2rem;">
                                    <i class="fas fa-info-circle" style="font-size: 2rem; color: #ccc; margin-bottom: 0.5rem; display: block;"></i>
                                    No donations yet. Make your first donation above!
                                 </div>
                             </div>
                        <?php endif; ?>
                    </tbody>
                 </div>
            </div>
        </div>
    </div>

    <script>
        // Auto-fill suggested amounts
        document.querySelectorAll('.amount-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const amount = this.getAttribute('data-amount');
                document.getElementById('amount').value = amount;
                
                // Add visual feedback
                document.querySelectorAll('.amount-btn').forEach(b => {
                    b.style.background = '#f5f5f5';
                    b.style.color = '#333';
                });
                this.style.background = '#2c5f2d';
                this.style.color = 'white';
            });
        });

        // File validation with JFIF support
        document.getElementById('proof').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if(file) {
                const fileExt = file.name.split('.').pop().toLowerCase();
                const validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'jfif'];
                const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'application/pdf', 'image/jfif', 'image/jpe'];
                
                if(!validExtensions.includes(fileExt) && !validTypes.includes(file.type)) {
                    alert('Please upload a valid file (JPG, JPEG, PNG, GIF, JFIF, PDF)');
                    this.value = '';
                } else if(file.size > 5 * 1024 * 1024) {
                    alert('File size must be less than 5MB');
                    this.value = '';
                } else {
                    // Show file name
                    const label = document.querySelector('.file-input-wrapper');
                    const small = document.createElement('small');
                    small.style.display = 'block';
                    small.style.marginTop = '0.5rem';
                    small.style.color = '#28a745';
                    small.innerHTML = '<i class="fas fa-check-circle"></i> Selected: ' + file.name;
                    
                    // Remove old message
                    const oldMsg = label.querySelector('small');
                    if(oldMsg && oldMsg !== label.querySelector('small:last-child')) {
                        oldMsg.remove();
                    }
                    if(!label.querySelector('small')) {
                        label.appendChild(small);
                    }
                }
            }
        });

        // Form submission confirmation
        document.getElementById('donationForm').addEventListener('submit', function(e) {
            const amount = document.getElementById('amount').value;
            const proof = document.getElementById('proof').value;
            
            if(!amount || amount <= 0) {
                e.preventDefault();
                alert('Please enter a valid donation amount');
                return false;
            }
            
            if(!proof) {
                e.preventDefault();
                alert('Please upload payment screenshot');
                return false;
            }
            
            if(confirm(`You are about to donate ₹${parseFloat(amount).toLocaleString('en-IN')}. Please ensure you have made the payment and uploaded correct screenshot.`)) {
                return true;
            } else {
                e.preventDefault();
                return false;
            }
        });
    </script>
</body>
</html>