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

// Get current KYC status
$user_query = $conn->query("SELECT kyc_status, kyc_doc, 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 = '';

// 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
                $db_path = "assets/uploads/kyc/" . $new_filename;
                $stmt = $conn->prepare("UPDATE users SET kyc_doc=?, kyc_status='pending' WHERE id=?");
                $stmt->bind_param("si", $db_path, $user_id);
                
                if ($stmt->execute()) {
                    $success_message = "✅ KYC document submitted successfully! Please wait for admin approval.";
                    $kyc_status = 'pending';
                } 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.";
                // Debug info (remove in production)
                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 */
        .status-banner {
            margin: 1.5rem;
            padding: 1rem;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .status-pending {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            color: #856404;
        }

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

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

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

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

        .user-info {
            background: #f8f9fa;
            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 #e0e0e0;
        }

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

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

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

        .file-upload {
            margin-bottom: 1.5rem;
        }

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

        .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;
        }

        /* 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;
            }
        }
    </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 to become a verified member</p>
            </div>

            <!-- Status Display -->
            <?php if($kyc_status == 'pending'): ?>
                <div class="status-banner status-pending">
                    <i class="fas fa-clock status-icon"></i>
                    <div>
                        <strong>KYC Status: Pending</strong><br>
                        <small>Your KYC is under review. You'll be notified once approved.Please check back later</small>
                    </div>
                </div>
            <?php elseif($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're now a verified member!</small>
                    </div>
                </div>
            <?php elseif($kyc_status == 'rejected'): ?>
                <div class="status-banner status-rejected">
                    <i class="fas fa-times-circle status-icon"></i>
                    <div>
                        <strong>KYC Status: Rejected</strong><br>
                        <small>Your KYC was rejected. Please submit a valid document.</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'): ?>
                <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. You don't need to submit again.
                </div>
            <?php else: ?>
                <!-- 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
                            </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" 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 both Side</li>
                                <li><i class="fas fa-check-circle"></i> Passport both side</li>
                                <li><i class="fas fa-check-circle"></i> Voter ID both side</li>
                                <li><i class="fas fa-check-circle"></i> Driving License both side</li>
                            </ul>
                        </div>

                        <!-- Submit Button -->
                        <button type="submit" class="submit-btn" id="submitBtn">
                            <i class="fas fa-paper-plane"></i>
                            Submit KYC for Verification
                        </button>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <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');

        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];
                const fileSize = file.size / 1024 / 1024; // in MB
                
                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
        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...';
        });

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

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

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

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

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

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

        dropArea.addEventListener('drop', handleDrop, false);

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