<?php
// /admin/admin_admission_create.php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

function err($msg)
{
    echo '<div class="card mt-3" style="background:#fff1f2;border-color:#fecaca;color:#991b1b">' . h($msg) . '</div>';
}
function ok($msg)
{
    echo '<div class="card mt-3" style="background:#f0fdf4;border-color:#86efac;color:#065f46">' . h($msg) . '</div>';
}

// Lookups
$courses = mysqli_query($conn, "SELECT id,name,fee_type,course_fee,monthly_fee,duration_months FROM courses WHERE is_active=1 ORDER BY name");

// Selected course for batch dropdown refresh
$selected_course_id = (int)($_POST['course_id'] ?? 0);
if (!$selected_course_id && $courses && mysqli_num_rows($courses) > 0) {
    $first = mysqli_fetch_assoc($courses);
    $selected_course_id = (int)$first['id'];
    mysqli_data_seek($courses, 0);
}

// Load batches for selected course
$batches = null;
if ($selected_course_id) {
    $stb = mysqli_prepare($conn, "SELECT id,name,start_date,status FROM batches WHERE course_id=? AND status IN ('Scheduled','Ongoing') ORDER BY start_date");
    mysqli_stmt_bind_param($stb, "i", $selected_course_id);
    mysqli_stmt_execute($stb);
    $batches = mysqli_stmt_get_result($stb);
    mysqli_stmt_close($stb);
}

// Handle create
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create' && hash_equals($CSRF, $_POST['csrf'] ?? '')) {
    $full_name      = trim($_POST['full_name'] ?? '');
    $father_name    = trim($_POST['father_name'] ?? '');
    $father_number  = trim($_POST['father_number'] ?? '');
    $gender         = trim($_POST['gender'] ?? '');
    $cnic           = trim($_POST['cnic'] ?? '');
    $dob            = $_POST['dob'] ?? '';
    $contact        = trim($_POST['contact_number'] ?? '');
    $email          = trim($_POST['email'] ?? '');
    $address        = trim($_POST['address'] ?? '');
    $course_id      = (int)($_POST['course_id'] ?? 0);
    $batch_id       = (int)($_POST['batch_id'] ?? 0);
    $pref_start     = $_POST['preferred_start_date'] ?? '';
    $init_fee       = isset($_POST['init_fee']) ? 1 : 0;

    if ($full_name === '' || $cnic === '' || !$course_id || !$batch_id) {
        $err = "Full name, CNIC, Course & Batch required.";
    } else {
        mysqli_begin_transaction($conn);

        // 1) find/create student by CNIC
        $student_id = 0;
        $st = mysqli_prepare($conn, "SELECT id FROM students WHERE cnic=? LIMIT 1");
        mysqli_stmt_bind_param($st, "s", $cnic);
        mysqli_stmt_execute($st);
        $res = mysqli_stmt_get_result($st);
        if ($row = mysqli_fetch_assoc($res)) $student_id = (int)$row['id'];
        mysqli_stmt_close($st);

        if (!$student_id) {
            $ins = mysqli_prepare($conn, "INSERT INTO students(full_name,father_name,father_number,gender,cnic,dob,contact_number,email,address,portal_enabled,created_at)
                                    VALUES (?,?,?,?,?,?,?,?,?,1,NOW())");
            mysqli_stmt_bind_param($ins, "sssssssss", $full_name, $father_name, $father_number, $gender, $cnic, $dob, $contact, $email, $address);
            mysqli_stmt_execute($ins);
            $student_id = mysqli_insert_id($conn);
            mysqli_stmt_close($ins);
        } else {
            // Update minimal fields on existing
            $up = mysqli_prepare($conn, "UPDATE students SET full_name=?, father_name=?, father_number=?, gender=?, dob=?, contact_number=?, email=?, address=? WHERE id=?");
            mysqli_stmt_bind_param($up, "ssssssssi", $full_name, $father_name, $father_number, $gender, $dob, $contact, $email, $address, $student_id);
            mysqli_stmt_execute($up);
            mysqli_stmt_close($up);
        }

        // Check if already registered same course & batch active
        $dup = mysqli_prepare($conn, "SELECT id FROM registrations WHERE student_id=? AND course_id=? AND batch_id=? AND status IN ('ACTIVE','COMPLETED','INACTIVE') LIMIT 1");
        mysqli_stmt_bind_param($dup, "iii", $student_id, $course_id, $batch_id);
        mysqli_stmt_execute($dup);
        $dupRes = mysqli_stmt_get_result($dup);
        $already = mysqli_fetch_assoc($dupRes);
        mysqli_stmt_close($dup);
        if ($already) {
            mysqli_rollback($conn);
            $err = "This student is already registered in the selected course & batch.";
        } else {
            // 2) Generate reg_no ZE-YYYY-####
            $year = date('Y');
            $cntRes = mysqli_query($conn, "SELECT COUNT(*)+1 AS n FROM registrations WHERE YEAR(approved_at)=$year");
            $seq = (int)mysqli_fetch_assoc($cntRes)['n'];
            $reg_no = sprintf("ZE-%s-%04d", $year, $seq);

            // 3) Insert registration (auto-approved)
            $approved_by = (int)($_SESSION['admin_id'] ?? 0);
            $insr = mysqli_prepare($conn, "INSERT INTO registrations(reg_no,student_id,course_id,batch_id,preferred_start_date,source,fee_status,status,requested_at,approved_at,approved_by)
                                     VALUES (? ,? ,? ,? ,? ,'admin_create','UNPAID','ACTIVE',NOW(),NOW(),?)");
            mysqli_stmt_bind_param($insr, "siiissi", $reg_no, $student_id, $course_id, $batch_id, $pref_start, $approved_by);
            mysqli_stmt_execute($insr);
            $registration_id = mysqli_insert_id($conn);
            mysqli_stmt_close($insr);

            // 4) Optional fee_payments init (compute total fee from course model)
            if ($init_fee) {
                $cr = mysqli_prepare($conn, "SELECT fee_type,course_fee,monthly_fee,duration_months FROM courses WHERE id=?");
                mysqli_stmt_bind_param($cr, "i", $course_id);
                mysqli_stmt_execute($cr);
                $cInfo = mysqli_stmt_get_result($cr);
                $c = mysqli_fetch_assoc($cInfo);
                mysqli_stmt_close($cr);

                $total_fee = 0;
                if ($c) {
                    if ($c['fee_type'] === 'PER_MONTH') {
                        $months = max(1, (int)$c['duration_months']);
                        $total_fee = (int)$c['monthly_fee'] * $months;
                    } else {
                        $total_fee = (int)$c['course_fee'];
                    }
                }

                $stf = mysqli_prepare($conn, "INSERT INTO fee_payments(student_id,course_id,total_fee,paid_amount,discount,extra_charges,status,remarks,updated_at)
                                      VALUES (?,?,?,0,0,0,'UNPAID','Auto-created by admin',NOW())");
                mysqli_stmt_bind_param($stf, "iii", $student_id, $course_id, $total_fee);
                mysqli_stmt_execute($stf);
                mysqli_stmt_close($stf);
            }

            mysqli_commit($conn);
            $ok = "Admission created and approved. Reg: $reg_no";
            header("Location: registrations.php?msg=" . urlencode($ok));
            exit;
        }
    }
}

admin_header('Create Admission (Admin)');
?>
<h2 style="margin:0 0 8px">Create Admission (Admin)</h2>
<p class="muted">Admin se create hone par registration <b>auto‑approved</b> ho jata hai.</p>
<?php if (!empty($err)) err($err); ?>

<div class="grid mt-3" style="grid-template-columns:repeat(12,1fr);gap:12px">
    <div class="card" style="grid-column:span 7">
        <h3 style="margin:0 0 10px;color:#2563eb">Student Info</h3>
        <form method="post">
            <input type="hidden" name="csrf" value="<?= $CSRF ?>">
            <input type="hidden" name="action" value="create">

            <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                <div style="grid-column:span 6"><label>Full Name</label><input name="full_name" required></div>
                <div style="grid-column:span 3"><label>Father Name</label><input name="father_name"></div>
                <div style="grid-column:span 3"><label>Father Number</label><input name="father_number" placeholder="03xx-xxxxxxx"></div>

                <div style="grid-column:span 3"><label>Gender</label>
                    <select name="gender">
                        <option>Male</option>
                        <option>Female</option>
                        <option>Other</option>
                    </select>
                </div>
                <div style="grid-column:span 3"><label>CNIC / B-Form</label><input name="cnic" required placeholder="12345-1234567-1"></div>
                <div style="grid-column:span 3"><label>DOB</label><input type="date" name="dob"></div>
                <div style="grid-column:span 3"><label>Contact</label><input name="contact_number" placeholder="03xx-xxxxxxx"></div>

                <div style="grid-column:span 6"><label>Email</label><input type="email" name="email"></div>
                <div style="grid-column:span 12"><label>Address</label><input name="address"></div>
            </div>

            <h3 class="mt-3" style="margin:10px 0;color:#2563eb">Course & Batch</h3>
            <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                <div style="grid-column:span 6">
                    <label>Course</label>
              <select id="course_id" name="course_id" required>

                        <option value="">— Select —</option>
                        <?php if ($courses): while ($c = mysqli_fetch_assoc($courses)): ?>
                                <option value="<?= $c['id'] ?>" <?= $selected_course_id == $c['id'] ? 'selected' : '' ?>><?= h($c['name']) ?></option>
                        <?php endwhile;
                        endif; ?>
                    </select>
                </div>
                <div style="grid-column:span 6">
                    <label>Batch</label>
                  <select id="batch_id" name="batch_id" required>

                        <option value="">— Select batch —</option>
                        <?php if ($batches): while ($b = mysqli_fetch_assoc($batches)): ?>
                                <option value="<?= $b['id'] ?>"><?= h($b['name']) ?> (<?= h($b['status']) ?> • <?= h($b['start_date']) ?>)</option>
                        <?php endwhile;
                        endif; ?>
                    </select>
                </div>
                <div style="grid-column:span 6">
                    <label>Preferred Start Date</label>
                    <input type="date" name="preferred_start_date">
                </div>
                <div style="grid-column:span 6;display:flex;align-items:flex-end;gap:10px">
                    <label style="display:flex;align-items:center;gap:6px">
                        <input type="checkbox" name="init_fee" value="1" style="width:auto;height:auto"> Create initial fee record
                    </label>
                    <button class="btn primary" style="margin-left:auto">Create Admission</button>
                </div>
            </div>
        </form>
    </div>

    <div class="card" style="grid-column:span 5">
        <h3 style="margin:0 0 8px">Tips</h3>
        <ul style="margin:0;padding-left:16px;color:#475569;line-height:1.6">
            <li>CNIC match par existing student auto‑attach hota hai.</li>
            <li>Batch list course ke mutabiq filter hoti hai.</li>
            <li>“Create initial fee record” par fee_payments row (UNPAID) ban jayegi.</li>
        </ul>
    </div>
</div>
<script>
    // DOM refs
    const courseSel = document.getElementById('course_id');
    const batchSel = document.getElementById('batch_id');

    // helper: batch select ko fill kare
    function fillBatches(list) {
        batchSel.innerHTML = '';
        if (!list || !list.length) {
            batchSel.innerHTML = '<option value="">No batches</option>';
            return;
        }
        list.forEach(b => {
            const opt = document.createElement('option');
            opt.value = b.id;
            opt.textContent = `${b.name} (${b.status} • ${b.start_date})`;
            batchSel.appendChild(opt);
        });
    }

    // course change -> AJAX fetch batches (no reload)
    courseSel.addEventListener('change', async () => {
        const cid = courseSel.value;
        batchSel.innerHTML = '<option>Loading...</option>';
        if (!cid) {
            batchSel.innerHTML = '<option value="">— Select course first —</option>';
            return;
        }

        try {
            const res = await fetch('get_batches.php?course_id=' + encodeURIComponent(cid));
            const data = await res.json();
            if (data && data.ok) fillBatches(data.rows);
            else fillBatches([]);
        } catch (e) {
            console.error(e);
            batchSel.innerHTML = '<option value="">Failed to load</option>';
        }
    });
</script>

<?php admin_footer(); ?>