<?php 
require_once '../db_connect.php';
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// Fetch active courses for dropdown
try {
    $courses = $pdo->query("SELECT id, title FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { die("Database Error: " . $e->getMessage()); }

$msg = ""; $msgType = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Data Collection & Sanitization
    $data = [
        'course_id'           => (int)$_POST['course_id'],
        'admission_type'      => $_POST['admission_type'] ?? 'Online',
        'payable_fee'         => $_POST['payable_fee'] ?? 0,
        'student_name'        => htmlspecialchars(trim($_POST['student_name'])),
        'father_husband_name' => htmlspecialchars(trim($_POST['father_husband_name'])),
        'mother_name'         => htmlspecialchars(trim($_POST['mother_name'])),
        'phone'               => htmlspecialchars(trim($_POST['phone'])),
        'email'               => filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL),
        'permanent_address'   => htmlspecialchars(trim($_POST['permanent_address'])),
        'present_address'     => htmlspecialchars(trim($_POST['present_address'])),
        'edu_ssc'             => htmlspecialchars(trim($_POST['edu_ssc'])),
        'edu_hsc'             => htmlspecialchars(trim($_POST['edu_hsc'])),
        'status'              => $_POST['status'] ?? 'pending',
        'payment_method'      => htmlspecialchars(trim($_POST['payment_method'])),
        'transaction_id'      => htmlspecialchars(trim($_POST['transaction_id'])),
        'payment_status'      => $_POST['payment_status'] ?? 'unpaid',
        'guardian_phone'      => htmlspecialchars(trim($_POST['guardian_phone'])),
        'referred_by'         => htmlspecialchars(trim($_POST['referred_by']))
    ];

    // File Upload logic
    $upload_dir = '../uploads/documents/';
    if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);

    $files = ['student_photo', 'document_path', 'payment_screenshot'];
    foreach ($files as $file_field) {
        $path = "";
        if (isset($_FILES[$file_field]) && $_FILES[$file_field]['error'] == 0) {
            $ext = pathinfo($_FILES[$file_field]['name'], PATHINFO_EXTENSION);
            $filename = $file_field . "_" . time() . "_" . rand(100, 999) . "." . $ext;
            if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $upload_dir . $filename)) {
                $path = 'uploads/documents/' . $filename;
            }
        }
        $data[$file_field] = $path;
    }

    try {
        $sql = "INSERT INTO admissions (
                    course_id, admission_type, payable_fee, student_name, father_husband_name, 
                    mother_name, phone, email, permanent_address, present_address, 
                    edu_ssc, edu_hsc, document_path, status, payment_method, 
                    transaction_id, payment_screenshot, payment_status, guardian_phone, 
                    student_photo, referred_by
                ) VALUES (
                    :course_id, :admission_type, :payable_fee, :student_name, :father_husband_name, 
                    :mother_name, :phone, :email, :permanent_address, :present_address, 
                    :edu_ssc, :edu_hsc, :document_path, :status, :payment_method, 
                    :transaction_id, :payment_screenshot, :payment_status, :guardian_phone, 
                    :student_photo, :referred_by
                )";
        
        $pdo->prepare($sql)->execute($data);
        $msg = "New admission record created successfully!"; $msgType = "success";
    } catch (PDOException $e) { 
        $msg = "Database Error: " . $e->getMessage(); $msgType = "danger"; 
    }
}
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    
    .main-content { background-color: var(--bg-soft); min-height: 100vh; }
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 35px; border-left: 6px solid var(--theme-green); }
    .custom-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.05); padding: 35px; border-top: 6px solid var(--theme-green); }
    
    .section-title { font-weight: 800; color: var(--theme-dark); font-size: 15px; margin-top: 30px; border-bottom: 2px dashed #e2e8f0; padding-bottom: 10px; margin-bottom: 25px; display: flex; align-items: center; text-transform: uppercase; letter-spacing: 1px; }
    .section-title i { color: var(--theme-gold); margin-right: 12px; font-size: 18px; }
    
    .form-label { font-weight: 700; color: #64748b; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
    .form-control, .form-select { border-radius: 12px; padding: 12px 18px; border: 2px solid #f1f5f9; background: var(--bg-soft); transition: 0.3s; font-size: 14px; color: var(--theme-dark); font-weight: 500;}
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); outline: none; }
    
    .btn-submit { background: var(--theme-green); color: #fff; padding: 15px 45px; border-radius: 50px; font-weight: 800; font-size: 16px; border: none; transition: 0.3s; box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }
    .btn-submit:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-3px); }

    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }

    /* --- 📱 Mobile Responsive Fixes --- */
    @media (max-width: 768px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .dashboard-header > a.btn { width: 100%; justify-content: center; } 
        
        /* Fixed Square Menu Button */
        #sidebarToggle { width: 42px !important; height: 42px !important; padding: 0; display: inline-flex !important; align-items: center; justify-content: center; flex-shrink: 0; border-radius: 8px;}
        .custom-card { padding: 25px 20px !important; }
        .btn-submit { width: 100%; }
    }
</style>

<div class="main-content p-4">
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-md-none me-3 shadow-sm" id="sidebarToggle">
                <i class="fas fa-bars text-dark"></i>
            </button>
            <div>
                <h4 class="mb-0 fw-bold text-dark">New Admission</h4>
                <p class="text-muted small mb-0 d-none d-md-block">Fill out the form below to enroll a new student.</p>
            </div>
        </div>
        <a href="view_admissions.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm text-dark text-decoration-none">
            <i class="fas fa-list me-2"></i> Back to List
        </a>
    </div>

    <?php if($msg): ?> 
        <div class="alert alert-<?= $msgType ?> border-0 border-start border-4 border-<?= $msgType ?> shadow-sm mb-4 fw-bold p-3 fade-up bg-white">
            <i class="fas fa-info-circle me-2"></i> <?= $msg ?>
        </div> 
    <?php endif; ?>

    <div class="custom-card fade-up">
        <form action="" method="POST" enctype="multipart/form-data">
            
            <div class="section-title mt-0"><i class="fas fa-user-circle"></i> Personal Information</div>
            <div class="row g-4">
                <div class="col-md-4">
                    <label class="form-label">Student Full Name *</label>
                    <input type="text" name="student_name" class="form-control" placeholder="E.g. John Doe" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Phone Number *</label>
                    <input type="text" name="phone" class="form-control" placeholder="+880..." required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Guardian Phone</label>
                    <input type="text" name="guardian_phone" class="form-control" placeholder="Emergency contact">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Father / Husband Name</label>
                    <input type="text" name="father_husband_name" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Mother's Name</label>
                    <input type="text" name="mother_name" class="form-control">
                </div>
                <div class="col-md-12">
                    <label class="form-label">Email Address</label>
                    <input type="email" name="email" class="form-control" placeholder="example@mail.com">
                </div>
            </div>

            <div class="section-title"><i class="fas fa-map-marked-alt"></i> Address & Academic Info</div>
            <div class="row g-4">
                <div class="col-md-6">
                    <label class="form-label">SSC / Equivalent Info</label>
                    <input type="text" name="edu_ssc" class="form-control" placeholder="Board, Year, GPA">
                </div>
                <div class="col-md-6">
                    <label class="form-label">HSC / Equivalent Info</label>
                    <input type="text" name="edu_hsc" class="form-control" placeholder="Board, Year, GPA">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Permanent Address</label>
                    <textarea name="permanent_address" class="form-control" rows="2" placeholder="Village/Area, Post, District"></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Present Address</label>
                    <textarea name="present_address" class="form-control" rows="2" placeholder="Current living address"></textarea>
                </div>
            </div>

            <div class="section-title"><i class="fas fa-graduation-cap"></i> Course & Payment Settings</div>
            <div class="row g-4">
                <div class="col-md-3">
                    <label class="form-label">Select Course *</label>
                    <select name="course_id" class="form-select fw-bold" style="color: var(--theme-green);" required>
                        <option value="">Choose...</option>
                        <?php foreach($courses as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['title']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Admission Type</label>
                    <select name="admission_type" class="form-select">
                        <option value="Online">Online</option>
                        <option value="Offline">Offline</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Payable Fee (BDT)</label>
                    <input type="number" name="payable_fee" class="form-control" placeholder="0.00">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Referred By</label>
                    <input type="text" name="referred_by" class="form-control" placeholder="Name or ID">
                </div>
            </div>

            <div class="row g-4 mt-1">
                <div class="col-md-3">
                    <label class="form-label">Payment Method</label>
                    <input type="text" name="payment_method" class="form-control" placeholder="bKash/Nagad/Bank">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Transaction ID</label>
                    <input type="text" name="transaction_id" class="form-control" placeholder="TrxID">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Payment Status</label>
                    <select name="payment_status" class="form-select fw-bold">
                        <option value="unpaid">Unpaid</option>
                        <option value="pending">Pending</option>
                        <option value="verified" class="text-success">Verified</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Application Status</label>
                    <select name="status" class="form-select fw-bold">
                        <option value="pending">Pending</option>
                        <option value="approved" class="text-success">Approved</option>
                    </select>
                </div>
            </div>

            <div class="section-title"><i class="fas fa-cloud-upload-alt"></i> Documents & Photos</div>
            <div class="row g-4">
                <div class="col-md-4">
                    <label class="form-label">Student Photo</label>
                    <input type="file" name="student_photo" class="form-control" accept="image/*">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Academic Document</label>
                    <input type="file" name="document_path" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Payment Screenshot</label>
                    <input type="file" name="payment_screenshot" class="form-control" accept="image/*">
                </div>
            </div>

            <div class="mt-5 text-center border-top pt-4">
                <button type="submit" class="btn-submit shadow">
                    <i class="fas fa-check-circle me-2"></i> Submit Enrollment
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

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