<?php
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'db_connect.php';
$success = ""; $error = "";

// Get pre-selected course from URL (If coming from Course Details page)
$selected_course_id = isset($_GET['course']) ? (int)$_GET['course'] : 0;

// 1. Fetch Courses & Fees (Cleaned up for new DB structure)
$courses = [];
try {
    $courses = $pdo->query("SELECT id, title, fee FROM courses WHERE status = 'active' ORDER BY title ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { 
    $error = "Failed to load courses: " . $e->getMessage(); 
}

// 2. Form Submission Handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $course_id = (int)($_POST['course_id'] ?? 0); 
    $admission_type = "online"; // Forced to online for Ahmad Academy
    
    // Fetch actual fee from DB to prevent tampering
    $payable_fee = 0;
    foreach($courses as $c) {
        if($c['id'] == $course_id) { $payable_fee = $c['fee']; break; }
    }
    
    $student_name = htmlspecialchars(trim($_POST['student_name'] ?? ''));
    $father_name = htmlspecialchars(trim($_POST['father_husband_name'] ?? '')); 
    $mother_name = htmlspecialchars(trim($_POST['mother_name'] ?? '')); 
    
    $phone = htmlspecialchars(trim($_POST['phone'] ?? '')); 
    $guardian_phone = htmlspecialchars(trim($_POST['guardian_phone'] ?? '')); 
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    
    $referred_by = htmlspecialchars(trim($_POST['referred_by'] ?? '')); 
    
    // Address Formatting
    $address_1 = htmlspecialchars(trim($_POST['address_line_1'] ?? ''));
    $address_2 = htmlspecialchars(trim($_POST['address_line_2'] ?? ''));
    $city = htmlspecialchars(trim($_POST['city'] ?? ''));
    $perm_address = "Street: " . $address_1 . ", State/Province: " . $address_2 . ", Country: " . $city;
    $present_address = htmlspecialchars(trim($_POST['present_address'] ?? '')); 
    
    // Education
    $edu_ssc = htmlspecialchars(trim($_POST['edu_ssc'] ?? '')); 
    $edu_hsc = htmlspecialchars(trim($_POST['edu_hsc'] ?? '')); 

    $upload_dir = 'uploads/documents/';
    if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }

    // 3. Student Photo Upload
    $photo_path = "";
    if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] == 0) {
        $photo_ext = strtolower(pathinfo($_FILES['student_photo']['name'], PATHINFO_EXTENSION));
        if (in_array($photo_ext, ["jpg", "jpeg", "png"])) {
            if ($_FILES['student_photo']['size'] <= 2000000) { 
                $photo_name = "photo_" . time() . "_" . rand(1000, 9999) . "." . $photo_ext;
                if (move_uploaded_file($_FILES["student_photo"]["tmp_name"], $upload_dir . $photo_name)) {
                    $photo_path = $upload_dir . $photo_name;
                }
            } else { $error = "Photo size must be less than 2MB."; }
        } else { $error = "Photo must be in JPG or PNG format."; }
    } else {
        $error = "Student passport-size photo is required.";
    }

    // 4. Document Upload
    $document_path = "";
    if (isset($_FILES['document']) && $_FILES['document']['error'] == 0 && empty($error)) {
        $doc_ext = strtolower(pathinfo($_FILES['document']['name'], PATHINFO_EXTENSION));
        if (in_array($doc_ext, ["jpg", "jpeg", "png", "pdf"])) {
            if ($_FILES['document']['size'] <= 5000000) {
                $doc_name = "doc_" . time() . "_" . rand(1000, 9999) . "." . $doc_ext;
                if (move_uploaded_file($_FILES["document"]["tmp_name"], $upload_dir . $doc_name)) {
                    $document_path = $upload_dir . $doc_name;
                }
            } else { $error = "Document size must be less than 5MB."; }
        } else { $error = "Document must be in JPG, PNG, or PDF format."; }
    }

    // 5. Database Insertion & Redirect
    if (empty($error)) {
        if (!empty($student_name) && !empty($phone) && !empty($course_id) && !empty($photo_path)) {
            try {
                // payable_fee added to the insert query
                $insert = $pdo->prepare("INSERT INTO admissions (course_id, admission_type, payable_fee, student_name, father_husband_name, mother_name, phone, guardian_phone, email, permanent_address, present_address, edu_ssc, edu_hsc, student_photo, document_path, referred_by, payment_status, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unpaid', 'pending')");
                $insert->execute([$course_id, $admission_type, $payable_fee, $student_name, $father_name, $mother_name, $phone, $guardian_phone, $email, $perm_address, $present_address, $edu_ssc, $edu_hsc, $photo_path, $document_path, $referred_by]);
                
                $admission_id = $pdo->lastInsertId();
                header("Location: payment.php?id=" . $admission_id);
                exit;
                
            } catch (PDOException $e) { 
                $error = "Sorry, the application could not be submitted. " . $e->getMessage(); 
            }
        } else { 
            $error = "Please provide all required (*) information."; 
        }
    }
}
include 'header.php'; 
?>

<style>
    :root {
        --primary: #064e3b;        
        --primary-light: #059669;  
        --primary-dark: #022c22;   
        --accent: #d4af37;         
        --white: #ffffff;          
        --bg-soft: #f8fafc;
    }
    
    body { background-color: var(--bg-soft); font-family: 'Outfit', sans-serif; overflow-x: hidden; }

    /* --- Hero Section --- */
    .page-hero {
        background: linear-gradient(135deg, rgba(2, 44, 34, 0.95), rgba(6, 78, 59, 0.95)),
                    url('https://www.transparenttextures.com/patterns/arabesque.png');
        padding: 80px 0 60px;
        color: var(--white);
        text-align: center;
        border-bottom: 5px solid var(--accent);
        position: relative;
    }
    .arabic-greeting { font-family: 'Amiri', serif; font-size: 32px; color: var(--accent); margin-bottom: 15px; display: block; }
    .page-hero h1 { font-weight: 900; font-size: 40px; margin-bottom: 15px; }

    /* --- Form Styling --- */
    .form-wrapper { 
        max-width: 950px; 
        margin: -40px auto 50px; 
        background: var(--white); 
        padding: 50px; 
        box-shadow: 0 20px 40px rgba(0,0,0,0.08); 
        border-radius: 20px; 
        border-top: 8px solid var(--accent); 
        position: relative;
        z-index: 10;
    }
    
    .form-label { font-weight: 700; color: var(--primary-dark); font-size: 15px; margin-bottom: 8px; }
    .form-control, .form-select { border-radius: 10px; padding: 14px 15px; border: 2px solid #e2e8f0; background-color: var(--bg-soft); transition: 0.3s; font-size: 15px; }
    .form-control:focus, .form-select:focus { border-color: var(--primary); background-color: var(--white); box-shadow: 0 0 0 0.25rem rgba(6, 78, 59, 0.1); }
    
    .section-title { font-weight: 800; margin-top: 40px; margin-bottom: 25px; color: var(--primary); font-size: 20px; border-bottom: 2px dashed #e2e8f0; padding-bottom: 12px; display: flex; align-items: center; }
    .section-title i { color: var(--accent); margin-right: 10px; font-size: 22px; }
    
    /* --- Payment Card --- */
    .payment-card { 
        background: linear-gradient(135deg, var(--primary-dark), var(--primary)); 
        color: white; 
        border-radius: 15px; 
        padding: 30px; 
        margin-top: 20px; 
        display: none; 
        border-left: 6px solid var(--accent);
        box-shadow: 0 10px 20px rgba(2, 44, 34, 0.15);
    }

    .payment-badge {
        font-weight: 700;
        font-size: 14px;
        transition: 0.3s;
        border: 2px solid transparent;
    }
    .payment-badge:hover { transform: translateY(-2px); }
    
    /* Brand Colors for Highlights */
    .badge-bkash { color: #e2136e; border-bottom: 3px solid #e2136e; }
    .badge-nagad { color: #ed1c24; border-bottom: 3px solid #ed1c24; }
    .badge-bank { color: #059669; border-bottom: 3px solid #059669; }
    
    .btn-submit { 
        background: var(--accent); 
        color: var(--primary-dark); 
        padding: 16px; 
        border-radius: 50px; 
        font-weight: 800; 
        font-size: 18px; 
        width: 100%; 
        border: none; 
        transition: 0.3s; 
        margin-top: 30px; 
        text-transform: uppercase;
        letter-spacing: 1px;
    }
    .btn-submit:hover { background: #c29d2b; transform: translateY(-3px); box-shadow: 0 10px 25px rgba(212, 175, 55, 0.4); }

    @media (max-width: 768px) {
        .form-wrapper { padding: 30px 20px; margin-top: -20px; }
        .payment-card { flex-direction: column; text-align: center; gap: 20px; }
        .payment-card .text-end { text-align: center !important; }
        .payment-methods-wrap { justify-content: center !important; }
    }
</style>

<section class="page-hero">
    <div class="container">
        <h1>Online Enrollment Form</h1>
        <p class="text-white-50 fs-5 mb-0">Join Ahmad Academy and start your journey of seeking authentic knowledge.</p>
    </div>
</section>

<div class="container pb-5">
    <div class="form-wrapper">
        
        <?php if($error): ?> 
            <div class="alert alert-danger border-0 border-start border-5 border-danger shadow-sm p-4 rounded-3 mb-5">
                <h6 class="fw-bold mb-1 text-danger"><i class="fas fa-exclamation-triangle me-2"></i> Error Processing Application!</h6>
                <p class="mb-0 text-dark"><?= $error; ?></p>
            </div> 
        <?php endif; ?>

        <form action="" method="POST" enctype="multipart/form-data">
            
            <input type="hidden" name="admission_type" value="online">

            <div class="row g-4">
                <div class="col-md-12"><div class="section-title mt-0"><i class="fas fa-book-quran"></i> Course Selection & Payment</div></div>
                
                <div class="col-md-12">
                    <label class="form-label">Select Your Desired Course <span class="text-danger fs-5">*</span></label>
                    <select name="course_id" id="course_id" class="form-select fw-bold" required onchange="updatePayment()">
                        <option value="">-- Choose a Course --</option>
                        <?php if(!empty($courses)): foreach($courses as $c): ?>
                            <option value="<?= $c['id'] ?>" data-fee="<?= $c['fee'] ?>" <?= ($c['id'] == $selected_course_id) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($c['title']) ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>
                
                <div class="col-md-12">
                    <div id="payment_display" class="payment-card align-items-center justify-content-between">
                        <div>
                            <p class="mb-1 text-white-50 small text-uppercase fw-bold letter-spacing-1">Total Course Fee</p>
                            <h2 class="mb-0 fw-bold" style="color: var(--accent);"><span id="fee_amount">$0.00</span></h2>
                        </div>
                        <div class="text-end">
                            <p class="mb-2 text-white-50 small text-uppercase fw-bold">Accepted Payment Methods</p>
                            <div class="d-flex flex-wrap gap-2 justify-content-end payment-methods-wrap">
                                <span class="badge bg-white py-2 px-3 payment-badge badge-bkash">
                                    <i class="fas fa-mobile-alt me-1"></i> bKash
                                </span>
                                <span class="badge bg-white py-2 px-3 payment-badge badge-nagad">
                                    <i class="fas fa-mobile-alt me-1"></i> Nagad
                                </span>
                                <span class="badge bg-white py-2 px-3 payment-badge badge-bank">
                                    <i class="fas fa-university me-1"></i> Bank Transfer
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row g-4 mt-2">
                <div class="col-md-12"><div class="section-title"><i class="fas fa-user-graduate"></i> Personal Information</div></div>

                <div class="col-md-6">
                    <label class="form-label">Full Name <span class="text-danger">*</span></label>
                    <input type="text" name="student_name" class="form-control" placeholder="As per official documents" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Email Address <span class="text-danger">*</span></label>
                    <input type="email" name="email" class="form-control" placeholder="example@email.com" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Personal Phone / WhatsApp <span class="text-danger">*</span></label>
                    <input type="tel" name="phone" class="form-control" placeholder="+1 XXXXX XXXXX" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Emergency Contact Number <span class="text-danger">*</span></label>
                    <input type="tel" name="guardian_phone" class="form-control border-warning" placeholder="+1 XXXXX XXXXX" required>
                </div>
                
                <div class="col-md-6">
                    <label class="form-label">Father / Guardian's Name <span class="text-danger">*</span></label>
                    <input type="text" name="father_husband_name" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Mother's Name <span class="text-danger">*</span></label>
                    <input type="text" name="mother_name" class="form-control" required>
                </div>
            </div>

            <div class="row g-4 mt-1">
                <div class="col-md-12"><div class="section-title"><i class="fas fa-map-marked-alt"></i> Address Details</div></div>
                
                <div class="col-md-12">
                    <label class="form-label text-muted">Home Country Address <span class="text-danger">*</span></label>
                    <div class="row g-3">
                        <div class="col-md-4"><input type="text" name="address_line_1" class="form-control" placeholder="Street Address / House No." required></div>
                        <div class="col-md-4"><input type="text" name="address_line_2" class="form-control" placeholder="State / Province" required></div>
                        <div class="col-md-4"><input type="text" name="city" class="form-control" placeholder="City / Country" required></div>
                    </div>
                </div>
                <div class="col-md-12 mt-3">
                    <label class="form-label">Current Residence Address <span class="text-danger">*</span></label>
                    <input type="text" name="present_address" class="form-control" placeholder="Full current address (if different from above)" required>
                </div>
            </div>

            <div class="row g-4 mt-1">
                <div class="col-md-12"><div class="section-title"><i class="fas fa-certificate"></i> Educational Background</div></div>
                
                <div class="col-md-6">
                    <label class="form-label">General Education Level</label>
                    <input type="text" name="edu_ssc" class="form-control" placeholder="e.g., High School, Bachelor's Degree">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Previous Islamic Studies (If Any)</label>
                    <input type="text" name="edu_hsc" class="form-control" placeholder="e.g., Basic Tajweed, None">
                </div>
            </div>

            <div class="row g-4 mt-1 mb-4">
                <div class="col-md-12"><div class="section-title"><i class="fas fa-cloud-upload-alt"></i> Required Documents</div></div>
                
                <div class="col-md-6">
                    <label class="form-label" style="color: var(--primary-light);">Student Profile Photo <span class="text-danger">*</span></label>
                    <input type="file" name="student_photo" class="form-control p-2 border-success bg-success bg-opacity-10" accept="image/jpeg, image/png" required>
                    <small class="text-muted d-block mt-1">JPG/PNG format only (Max 2MB)</small>
                </div>
                <div class="col-md-6">
                    <label class="form-label">National ID / Passport / Certificate</label>
                    <input type="file" name="document" class="form-control p-2" accept="image/jpeg, image/png, application/pdf">
                    <small class="text-muted d-block mt-1">Optional (JPG/PNG/PDF Max 5MB)</small>
                </div>
                
                <div class="col-md-12 mt-4">
                    <label class="form-label text-muted">Referred By (Optional)</label>
                    <input type="text" name="referred_by" class="form-control border-light bg-white" placeholder="Enter Referral Name or Student ID">
                </div>
            </div>

            <button type="submit" class="btn-submit shadow-sm">
                Confirm Enrollment & Proceed to Payment <i class="fas fa-arrow-right ms-2"></i>
            </button>
        </form>
    </div>
</div>

<script>
    function updatePayment() {
        const courseSelect = document.getElementById('course_id');
        const paymentDisplay = document.getElementById('payment_display');
        const feeAmountSpan = document.getElementById('fee_amount');

        if (courseSelect.selectedIndex > 0) {
            const selectedOption = courseSelect.options[courseSelect.selectedIndex];
            
            // Get actual fee
            let fee = parseFloat(selectedOption.getAttribute('data-fee')) || 0;
            
            // Format fee to Dollar ($)
            feeAmountSpan.innerText = "$" + fee.toFixed(2);
            
            paymentDisplay.style.display = 'flex';
        } else {
            paymentDisplay.style.display = 'none';
        }
    }

    // Auto-run on page load to show fee if course is pre-selected from URL
    document.addEventListener("DOMContentLoaded", function() {
        updatePayment();
    });
</script>

<?php include 'footer.php'; ?>