<?php
if (!function_exists('setFlashMessage')) {
    function setFlashMessage($type, $msg) {
        $_SESSION['flash_' . $type] = $msg;
    }
}
ini_set("display_errors", 1);
error_reporting(E_ALL);
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();
$id = $_GET['id'] ?? ($_POST['student_id'] ?? 0);

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

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customData = [
        'student' => [
            'full_name' => $_POST['full_name'] ?? '',
            'father_name' => $_POST['father_name'] ?? '',
            'mother_name' => $_POST['mother_name'] ?? '',
            'roll_number' => $_POST['roll_number'] ?? '',
            'registration_number' => $_POST['registration_number'] ?? ''
        ],
        'course' => [
            'course_name' => $_POST['course_name'] ?? '',
            'course_code' => $_POST['course_code'] ?? ''
        ],
        'institution' => [
            'institution_name' => $_POST['institution_name'] ?? '',
            'institution_code' => $_POST['institution_code'] ?? ''
        ],
        'subjects' => []
    ];
    
    if (isset($_POST['subjects']) && is_array($_POST['subjects'])) {
        foreach ($_POST['subjects'] as $sub_id => $details) {
            $customData['subjects'][$sub_id] = [
                'date' => $details['date'] ?? '',
                'time' => $details['time'] ?? '10:00 to 1:00'
            ];
        }
    }
    
    $exam_session = $_POST['exam_session'] ?? '';
    $exam_type = strtolower($_POST['exam_type'] ?? 'annual');
    $exam_centre = $_POST['exam_centre'] ?? '';
    
    $json = json_encode($customData, JSON_UNESCAPED_UNICODE);
    
    $existing = $db->fetchOne("SELECT id FROM admit_cards WHERE student_id = ? LIMIT 1", [$id]);
    
    if ($existing) {
        $db->query("UPDATE admit_cards SET exam_session=?, exam_type=?, exam_centre=?, custom_data=? WHERE id=?", 
            [$exam_session, $exam_type, $exam_centre, $json, $existing['id']]);
    } else {
        $acn = 'AC-' . date('Y') . '-' . str_pad($id, 5, '0', STR_PAD_LEFT);
        $db->query("INSERT INTO admit_cards (student_id, admit_card_number, exam_session, exam_type, exam_centre, custom_data, generated_by, generated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            [$id, $acn, $exam_session, $exam_type, $exam_centre, $json, $_SESSION['user_id'], date('Y-m-d H:i:s')]);
    }
    
    // Handle Photo Upload
    if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] === UPLOAD_ERR_OK) {
        $photoDir = __DIR__ . '/../uploads/students/photos/';
        if (!is_dir($photoDir)) mkdir($photoDir, 0755, true);
        
        $ext = pathinfo($_FILES['student_photo']['name'], PATHINFO_EXTENSION);
        $fn = 'photo_override_' . $id . '_' . time() . '.' . $ext;
        
        if (move_uploaded_file($_FILES['student_photo']['tmp_name'], $photoDir . $fn)) {
            $photoPath = 'uploads/students/photos/' . $fn;
            $db->query("UPDATE students SET photo_path = ? WHERE id = ?", [$photoPath, $id]);
        }
    }
    
    setFlashMessage('success', 'Full admit card overrides & photo saved successfully!');
    header("Location: admit-cards.php");
    exit;
}

// Fetch base student details
$s = $db->fetchOne("
    SELECT s.*, c.course_name, c.course_code, u.institution_name, u.institution_code 
    FROM students s 
    LEFT JOIN courses c ON s.course_id = c.id 
    LEFT JOIN users u ON s.institution_id = u.id 
    WHERE s.id = ?
", [$id]);

if (!$s) die("Student not found.");

$subjects = $db->fetchAll("SELECT * FROM subjects WHERE course_id = ? ORDER BY type, subject_name", [$s['course_id']]);
$admitCard = $db->fetchOne("SELECT * FROM admit_cards WHERE student_id = ? LIMIT 1", [$id]);

$cData = [];
if (!empty($admitCard['custom_data'])) {
    $cData = json_decode($admitCard['custom_data'], true);
}

// Merge overrides
$val = function($section, $key, $default) use ($cData) {
    if (isset($cData[$section][$key]) && $cData[$section][$key] !== '') return $cData[$section][$key];
    return $default;
};

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Full Editor - <?= htmlspecialchars($s['full_name']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
</head>
<body class="bg-light">
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-edit me-2 text-primary"></i> Full Admit Card Editor</h2>
                    <a href="admit-cards.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
                </div>

                <div class="alert alert-warning mb-4 shadow-sm">
                    <strong>Note:</strong> Changes made here ONLY affect what is printed on the Admit Card. They do NOT change the student's original registration profile. Leave fields exactly as they are to use defaults.
                </div>

                <form method="POST" enctype="multipart/form-data" class="needs-validation">
                    <input type="hidden" name="student_id" value="<?= $s['id'] ?>">

                    <div class="card shadow-sm border-0 mb-4 rounded-4">
                        <div class="card-header bg-primary text-white py-3 rounded-top-4">
                            <h5 class="mb-0">1. Student Details</h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label>Student Name</label>
                                    <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($val('student', 'full_name', $s['full_name'])) ?>">
                                </div>
                                <div class="col-md-4">
                                    <label>Father's Name</label>
                                    <input type="text" name="father_name" class="form-control" value="<?= htmlspecialchars($val('student', 'father_name', $s['father_name'])) ?>">
                                </div>
                                <div class="col-md-4">
                                    <label>Mother's Name</label>
                                    <input type="text" name="mother_name" class="form-control" value="<?= htmlspecialchars($val('student', 'mother_name', $s['mother_name'])) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label>Roll Number</label>
                                    <input type="text" name="roll_number" class="form-control" value="<?= htmlspecialchars($val('student', 'roll_number', $s['roll_number'])) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label>Registration/Enrollment No</label>
                                    <input type="text" name="registration_number" class="form-control" value="<?= htmlspecialchars($val('student', 'registration_number', $s['registration_number'])) ?>">
                                </div>
                                <div class="col-md-12">
                                    <label>Update Student Photo (Optional)</label>
                                    <input type="file" name="student_photo" class="form-control" accept="image/*">
                                    <div class="form-text text-danger">Note: Uploading a photo here will permanently update the student's actual profile photo!</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0 mb-4 rounded-4">
                        <div class="card-header bg-primary text-white py-3 rounded-top-4">
                            <h5 class="mb-0">2. Academic & Center Details</h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label>Course Name</label>
                                    <input type="text" name="course_name" class="form-control" value="<?= htmlspecialchars($val('course', 'course_name', $s['course_name'])) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label>College Name</label>
                                    <input type="text" name="institution_name" class="form-control" value="<?= htmlspecialchars($val('institution', 'institution_name', $s['institution_name'])) ?>">
                                </div>
                                <div class="col-md-4">
                                    <label>Exam Session</label>
                                    <input type="text" name="exam_session" class="form-control" value="<?= htmlspecialchars($admitCard['exam_session'] ?? $s['session_year']) ?>">
                                </div>
                                <div class="col-md-4">
                                    <label>Exam Type</label>
                                    <input type="text" name="exam_type" class="form-control" value="<?= htmlspecialchars($admitCard['exam_type'] ?? 'Annual') ?>">
                                </div>
                                <div class="col-md-4">
                                    <label>Exam Centre</label>
                                    <input type="text" name="exam_centre" class="form-control" value="<?= htmlspecialchars($admitCard['exam_centre'] ?? ($s['institution_name'] . ' (SELF CENTER)')) ?>">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow-sm border-0 mb-4 rounded-4">
                        <div class="card-header bg-primary text-white py-3 rounded-top-4">
                            <h5 class="mb-0">3. Custom Subject Schedule</h5>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table mb-0 align-middle">
                                    <thead class="bg-light">
                                        <tr>
                                            <th class="ps-3">Subject Name</th>
                                            <th>Subject Code</th>
                                            <th>Custom Exam Date</th>
                                            <th>Custom Exam Time</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $baseDate = strtotime('next monday');
                                        $i = 0;
                                        foreach ($subjects as $sub): 
                                            $i++;
                                            $defDate = date('d-m-Y', strtotime("+$i days", $baseDate));
                                            
                                            $cDate = $cData['subjects'][$sub['id']]['date'] ?? '';
                                            $cTime = $cData['subjects'][$sub['id']]['time'] ?? '10:00 to 1:00';
                                        ?>
                                        <tr>
                                            <td class="ps-3 fw-bold"><?= htmlspecialchars($sub['subject_name']) ?></td>
                                            <td><?= htmlspecialchars($sub['subject_code']) ?></td>
                                            <td>
                                                <input type="text" name="subjects[<?= $sub['id'] ?>][date]" class="form-control form-control-sm" placeholder="e.g. <?= $defDate ?>" value="<?= htmlspecialchars($cDate) ?>">
                                            </td>
                                            <td>
                                                <input type="text" name="subjects[<?= $sub['id'] ?>][time]" class="form-control form-control-sm" value="<?= htmlspecialchars($cTime) ?>">
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                        <?php if(empty($subjects)): ?>
                                        <tr><td colspan="4" class="text-center py-4">No subjects found for this course.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="text-end mb-5">
                        <button type="submit" class="btn btn-primary btn-lg px-5 shadow-sm rounded-pill"><i class="fas fa-save me-2"></i> Save All Customizations</button>
                    </div>
                </form>
            </main>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
