<?php
/**
 * Save / Update Admit Card details
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db = DB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = intval($_POST['student_id'] ?? 0);
    $exam_session = trim($_POST['exam_session'] ?? '');
    $exam_type = trim($_POST['exam_type'] ?? 'annual');
    $exam_centre = trim($_POST['exam_centre'] ?? '');
    $exam_date_from = trim($_POST['exam_date_from'] ?? '');

    if (!$student_id) {
        setFlashMessage('error', 'Invalid student ID.');
        header("Location: admit-cards.php");
        exit;
    }

    // Check if record exists
    $existing = $db->fetchOne("SELECT id FROM admit_cards WHERE student_id = ? ORDER BY id DESC LIMIT 1", [$student_id]);

    $data = [];
    if (!empty($exam_session)) $data['exam_session'] = $exam_session;
    if (!empty($exam_type)) $data['exam_type'] = $exam_type;
    if (!empty($exam_centre)) $data['exam_centre'] = $exam_centre;
    if (!empty($exam_date_from)) $data['exam_date_from'] = $exam_date_from;

    if (empty($data)) {
        setFlashMessage('warning', 'No details provided to save.');
        header("Location: admit-cards.php");
        exit;
    }

    if ($existing) {
        // Update
        $updates = [];
        $params = [];
        foreach ($data as $k => $v) {
            $updates[] = "$k = ?";
            $params[] = $v;
        }
        $params[] = $existing['id'];
        
        $sql = "UPDATE admit_cards SET " . implode(", ", $updates) . " WHERE id = ?";
        $db->execute($sql, $params);
    } else {
        // Insert
        // We need admit_card_number which is unique
        $admit_card_number = 'AC-' . date('Y') . '-' . str_pad($student_id, 5, '0', STR_PAD_LEFT);
        
        $data['student_id'] = $student_id;
        $data['admit_card_number'] = $admit_card_number;
        $data['generated_by'] = $_SESSION['user_id'] ?? null;
        $data['generated_at'] = date('Y-m-d H:i:s');
        
        $columns = implode(", ", array_keys($data));
        $placeholders = implode(", ", array_fill(0, count($data), '?'));
        
        $sql = "INSERT INTO admit_cards ($columns) VALUES ($placeholders)";
        $db->execute($sql, array_values($data));
    }

    setFlashMessage('success', 'Admit card details saved successfully. You can now generate the admit card.');
    header("Location: admit-cards.php");
    exit;
}

header("Location: admit-cards.php");
exit;
