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

// Get current KYC status - FIXED: Only select existing columns
$user_query = $conn->query("SELECT kyc_status, name FROM users WHERE id=$user_id");
$user = $user_query->fetch_assoc();
$kyc_status = $user['kyc_status'];
$user_name = $user['name'];

$success_message = '';
$error_message = '';
$redirect_to_payment = false;

// Create necessary directories if they don't exist
function createDirectories() {
    $directories = [
        '../assets/',
        '../assets/uploads/',
        '../assets/uploads/kyc/',
        '../assets/uploads/payment_proof/',
        '../assets/uploads/id_cards/'
    ];
    
    foreach ($directories as $dir) {
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
    }
}

// Create directories
createDirectories();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_FILES['kyc_doc']) && $_FILES['kyc_doc']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'pdf'];
        $filename = $_FILES['kyc_doc']['name'];
        $fileext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $file_size = $_FILES['kyc_doc']['size'];
        $max_size = 5 * 1024 * 1024; // 5MB
        
        // Validate file size
        if ($file_size > $max_size) {
            $error_message = "❌ File size must be less than 5MB. Your file is " . round($file_size / 1024 / 1024, 2) . "MB.";
        }
        // Validate file extension
        elseif (!in_array($fileext, $allowed)) {
            $error_message = "❌ Invalid file type. Please upload JPG, JPEG, PNG, or PDF files only.";
        }
        else {
            $new_filename = "kyc_" . $user_id . "_" . time() . "_" . rand(1000, 9999) . "." . $fileext;
            $target = "../assets/uploads/kyc/" . $new_filename;
            
            // Try to move the uploaded file
            if (move_uploaded_file($_FILES['kyc_doc']['tmp_name'], $target)) {
                // Update database with relative path and AUTO APPROVE
                $db_path = "assets/uploads/kyc/" . $new_filename;
                
                // First check if kyc_doc column exists, if not, add it
                $check_column = $conn->query("SHOW COLUMNS FROM users LIKE 'kyc_doc'");
                if ($check_column->num_rows == 0) {
                    // Add kyc_doc column if it doesn't exist
                    $conn->query("ALTER TABLE users ADD COLUMN kyc_doc VARCHAR(255) DEFAULT NULL");
                }
                
                $stmt = $conn->prepare("UPDATE users SET kyc_doc=?, kyc_status='approved' WHERE id=?");
                $stmt->bind_param("si", $db_path, $user_id);
                
                if ($stmt->execute()) {
                    $success_message = "✅✅✅ KYC document submitted and AUTO-APPROVED successfully!";
                    $kyc_status = 'approved';
                    $redirect_to_payment = true;
                    
                    // Set session flag for celebration
                    $_SESSION['kyc_just_approved'] = true;
                } else {
                    $error_message = "❌ Database error. Please try again.";
                    // Delete uploaded file if database update fails
                    if (file_exists($target)) {
                        unlink($target);
                    }
                }
                $stmt->close();
            } else {
                $error_message = "❌ Failed to upload file. Please check folder permissions and try again.";
                error_log("Upload error - Temp file: " . $_FILES['kyc_doc']['tmp_name'] . " Target: " . $target);
            }
        }
    } else {
        $error_message = "❌ Please select a file to upload.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit KYC - BMYA-SHELDANG</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&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: 600px;
            margin: 0 auto;
        }

        /* Header */
        .header {
            background: white;
            padding: 1rem 2rem;
            border-radius: 15px;
            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;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #2c5f2d, #1a3a1a);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 1.5rem;
            color: #ffd700;
        }

        .logo h2 {
            color: #1a3a1a;
            font-size: 1.2rem;
            font-weight: 600;
        }

        .back-btn {
            background: #f0f0f0;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            color: #333;
            transition: all 0.3s;
        }

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

        /* Main Card */
        .kyc-card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2);
            animation: slideUp 0.5s ease;
        }

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

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

        .card-header i {
            font-size: 3rem;
            margin-bottom: 1rem;
        }

        .card-header h1 {
            font-size: 1.8rem;
            margin-bottom: 0.5rem;
        }

        .card-header p {
            opacity: 0.9;
            font-size: 0.9rem;
        }

        /* Status Banner - REMOVED PENDING MESSAGE */
        .status-banner {
            margin: 1.5rem;
            padding: 1rem;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .status-approved {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            border-left: 4px solid #28a745;
            color: #155724;
        }

        .celebration-banner {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            color: #856404;
            border: 2px solid #ffc107;
            animation: pulse 1s ease;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }

        .status-icon {
            font-size: 1.5rem;
        }

        /* Form */
        .form-container {
            padding: 2rem;
        }

        .user-info {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
        }

        .user-info-item {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #dee2e6;
        }

        .user-info-item:last-child {
            border-bottom: none;
        }

        .user-info-label {
            font-weight: 600;
            color: #495057;
        }

        .user-info-value {
            color: #1a3a1a;
            font-weight: 500;
        }

        /* File Upload */
        .file-upload {
            margin-bottom: 1.5rem;
        }

        .file-upload-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #333;
        }

        .file-upload-label i {
            color: #2c5f2d;
            margin-right: 0.5rem;
        }

        .file-upload-area {
            border: 2px dashed #ccc;
            border-radius: 12px;
            padding: 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #fafafa;
        }

        .file-upload-area:hover {
            border-color: #2c5f2d;
            background: #f0f9f0;
        }

        .file-upload-area i {
            font-size: 2rem;
            color: #2c5f2d;
            margin-bottom: 0.5rem;
        }

        .file-upload-area p {
            color: #666;
            font-size: 0.9rem;
        }

        .file-upload-area .file-name {
            margin-top: 0.5rem;
            color: #2c5f2d;
            font-weight: 500;
        }

        .file-input {
            display: none;
        }

        /* Requirements */
        .requirements {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
        }

        .requirements h4 {
            margin-bottom: 0.5rem;
            color: #333;
            font-size: 0.9rem;
        }

        .requirements ul {
            list-style: none;
            padding-left: 0;
        }

        .requirements li {
            padding: 0.25rem 0;
            font-size: 0.85rem;
            color: #666;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .requirements li i {
            font-size: 0.7rem;
            color: #2c5f2d;
        }

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

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        }

        .submit-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

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

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            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;
        }

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

        /* Redirect Overlay */
        .redirect-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .redirect-content {
            text-align: center;
            color: white;
        }

        .redirect-spinner {
            width: 80px;
            height: 80px;
            border: 8px solid rgba(255,255,255,0.3);
            border-top: 8px solid #ffd700;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .redirect-content h2 {
            margin-bottom: 10px;
            font-size: 1.5rem;
        }

        .redirect-content p {
            color: rgba(255,255,255,0.8);
        }

        .redirect-progress {
            width: 300px;
            height: 4px;
            background: rgba(255,255,255,0.2);
            border-radius: 2px;
            margin-top: 20px;
            overflow: hidden;
        }

        .redirect-progress-bar {
            width: 0%;
            height: 100%;
            background: #ffd700;
            animation: progress 3s ease forwards;
        }

        @keyframes progress {
            from { width: 0%; }
            to { width: 100%; }
        }

        /* Responsive */
        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }

            .card-header h1 {
                font-size: 1.4rem;
            }

            .form-container {
                padding: 1.5rem;
            }

            .file-upload-area {
                padding: 1.5rem;
            }
            
            .redirect-progress {
                width: 250px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="logo">
                <div class="logo-icon">
                    <i class="fas fa-id-card"></i>
                </div>
                <h2>BMYA-SHELDANG</h2>
            </div>
            <a href="dashboard.php" class="back-btn">
                <i class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
        </div>

        <!-- KYC Card -->
        <div class="kyc-card">
            <div class="card-header">
                <i class="fas fa-id-card"></i>
                <h1>KYC Verification</h1>
                <p>Submit your identity proof for instant verification</p>
            </div>

            <!-- Status Display - NO MORE PENDING MESSAGE -->
            <?php if($kyc_status == 'approved'): ?>
                <div class="status-banner status-approved">
                    <i class="fas fa-check-circle status-icon"></i>
                    <div>
                        <strong>✅ KYC Status: Approved</strong><br>
                        <small>Your identity has been verified. You can now make donations!</small>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Celebration Banner for Just Approved -->
            <?php if(isset($_SESSION['kyc_just_approved']) && $_SESSION['kyc_just_approved']): 
                unset($_SESSION['kyc_just_approved']);
            ?>
                <div class="status-banner celebration-banner">
                    <i class="fas fa-trophy status-icon"></i>
                    <div>
                        <strong>🎉 Congratulations! KYC Auto-Approved! 🎉</strong><br>
                        <small>Your document has been verified instantly. You're now ready to donate!</small>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Alert Messages -->
            <?php if($success_message): ?>
                <div class="alert alert-success" style="margin: 0 1.5rem;">
                    <i class="fas fa-check-circle"></i>
                    <?= htmlspecialchars($success_message) ?>
                </div>
            <?php endif; ?>

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

            <?php if($kyc_status == 'approved' && !isset($_SESSION['kyc_just_approved'])): ?>
                <div class="alert alert-info" style="margin: 0 1.5rem 1.5rem 1.5rem;">
                    <i class="fas fa-info-circle"></i>
                    Your KYC is already approved. 
                    <a href="upload_payment.php" style="color: #0c5460; font-weight: 600;">Click here to make a donation →</a>
                </div>
            <?php elseif($kyc_status != 'approved'): ?>
                <!-- Simple Form -->
                <form method="POST" enctype="multipart/form-data" id="kycForm">
                    <div class="form-container">
                        <!-- User Information -->
                        <div class="user-info">
                            <div class="user-info-item">
                                <span class="user-info-label">Name:</span>
                                <span class="user-info-value"><?= htmlspecialchars($user_name) ?></span>
                            </div>
                            <div class="user-info-item">
                                <span class="user-info-label">Member ID:</span>
                                <span class="user-info-value">#<?= str_pad($user_id, 6, '0', STR_PAD_LEFT) ?></span>
                            </div>
                        </div>

                        <!-- File Upload -->
                        <div class="file-upload">
                            <label class="file-upload-label">
                                <i class="fas fa-upload"></i> Upload ID Proof (Aadhar/PAN/Passport)
                            </label>
                            <div class="file-upload-area" onclick="document.getElementById('file-input').click()">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p>Click to browse or drag and drop</p>
                                <p style="font-size: 0.8rem; color: #999;">Supported: JPG, JPEG, PNG, PDF (Max 5MB)</p>
                                <div id="fileName" class="file-name"></div>
                            </div>
                            <input type="file" name="kyc_doc" id="file-input" class="file-input" accept=".jpg,.jpeg,.png,.pdf" required>
                        </div>

                        <!-- Requirements -->
                        <div class="requirements">
                            <h4><i class="fas fa-info-circle"></i> Accepted Documents with Full Address:</h4>
                            <ul>
                                <li><i class="fas fa-check-circle"></i> Aadhar Card</li>
                                <li><i class="fas fa-check-circle"></i> Passport</li>
                                <li><i class="fas fa-check-circle"></i> Voter ID</li>
                                <li><i class="fas fa-check-circle"></i> Driving License</li>
                            </ul>
                            <div class="help-text" style="margin-top: 10px; font-size: 0.75rem; color: #28a745;">
                                <i class="fas fa-star"></i> 
                                <strong>Instant Auto-Approval:</strong> Your KYC will be approved immediately after submission!
                            </div>
                        </div>

                        <!-- Submit Button -->
                        <button type="submit" class="submit-btn" id="submitBtn">
                            <i class="fas fa-paper-plane"></i>
                            Submit & Get Auto-Approval
                        </button>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <!-- Redirect Overlay -->
    <?php if($redirect_to_payment && $success_message): ?>
    <div class="redirect-overlay" id="redirectOverlay">
        <div class="redirect-content">
            <div class="redirect-spinner"></div>
            <h2><i class="fas fa-check-circle" style="color: #28a745;"></i> KYC Auto-Approved!</h2>
            <p>Redirecting to payment page...</p>
            <div class="redirect-progress">
                <div class="redirect-progress-bar"></div>
            </div>
        </div>
    </div>

    <script>
        // Auto redirect to payment page after 3 seconds
        setTimeout(function() {
            window.location.href = 'upload_payment.php';
        }, 3000);
    </script>
    <?php endif; ?>

    <script>
        // File upload preview
        const fileInput = document.getElementById('file-input');
        const fileName = document.getElementById('fileName');
        const submitBtn = document.getElementById('submitBtn');
        const form = document.getElementById('kycForm');

        if (fileInput) {
            fileInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    const file = this.files[0];
                    const fileSize = file.size / 1024 / 1024;
                    
                    if (fileSize > 5) {
                        alert('File size must be less than 5MB');
                        this.value = '';
                        fileName.innerHTML = '';
                        return;
                    }
                    
                    // Show file info
                    const fileExt = file.name.split('.').pop().toLowerCase();
                    const fileIcon = fileExt === 'pdf' ? 'fa-file-pdf' : 'fa-file-image';
                    fileName.innerHTML = '<i class="fas ' + fileIcon + '"></i> ' + file.name + ' (' + fileSize.toFixed(2) + ' MB)';
                    fileName.style.color = '#2c5f2d';
                } else {
                    fileName.innerHTML = '';
                }
            });
        }

        // Form validation
        if (form) {
            form.addEventListener('submit', function(e) {
                if (!fileInput.files || !fileInput.files[0]) {
                    e.preventDefault();
                    alert('Please select a file to upload');
                    return false;
                }
                
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting & Auto-Approving...';
            });
        }

        // Drag and drop functionality
        const dropArea = document.querySelector('.file-upload-area');
        
        if (dropArea) {
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, preventDefaults, false);
            });

            ['dragenter', 'dragover'].forEach(eventName => {
                dropArea.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, unhighlight, false);
            });
        }

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        function highlight() {
            if (dropArea) {
                dropArea.style.borderColor = '#2c5f2d';
                dropArea.style.background = '#f0f9f0';
            }
        }

        function unhighlight() {
            if (dropArea) {
                dropArea.style.borderColor = '#ccc';
                dropArea.style.background = '#fafafa';
            }
        }

        if (dropArea) {
            dropArea.addEventListener('drop', handleDrop, false);
        }

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            if (fileInput) {
                fileInput.files = files;
                // Trigger change event
                const event = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(event);
            }
        }
    </script>
</body>
</html>