<?php

require_once __DIR__ . '/../library/auth.php';

require_once __DIR__ . '/../library/audit_log.php';

$school_id = $_SESSION['school_id'];

$current_session_id = get_current_session_id($pdo);

allow_roles(['admin', 'accountant']);

$classes = [];

$students = [];

$message = '';


// ======================================================
// HANDLE FORM SUBMIT
// ======================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $class_id   = (int)($_POST['class_id'] ?? 0);

    $student_id = (int)($_POST['student_id'] ?? 0);


    // ==================================================
    // VALIDATION
    // ==================================================

    if ($class_id <= 0 || $student_id <= 0) {

        $message = '

            <div class="alert alert-warning">

                Please select both Class and Student!

            </div>

        ';
    }

    else {

        // ==================================================
        // FETCH STUDENT
        // ==================================================

        $stmt = $pdo->prepare("

            SELECT

                s.id,
                s.name,
                s.gender,
                s.dob,

                ss.roll_no,
                ss.admission_no,
                ss.class_id,
                ss.status,

                c.class_name

            FROM student_sessions ss

            INNER JOIN students s
                ON ss.student_id = s.id

            INNER JOIN classes c
                ON ss.class_id = c.id

            WHERE s.id = ?
            AND ss.class_id = ?
            AND ss.school_id = ?
            AND ss.session_id = ?
            AND ss.status = 'Active'

            LIMIT 1

        ");

        $stmt->execute([

            $student_id,
            $class_id,
            $school_id,
            $current_session_id

        ]);

        $student = $stmt->fetch(PDO::FETCH_ASSOC);


        // ==================================================
        // INVALID STUDENT
        // ==================================================

        if (!$student) {

            $message = '

                <div class="alert alert-danger">

                    Invalid Student or Inactive!

                </div>

            ';
        }

        else {

            // ==================================================
            // CHECK EXISTING TC
            // ==================================================

            $check_tc = $pdo->prepare("

                SELECT id

                FROM tc_certificates

                WHERE school_id = ?
                AND session_id = ?
                AND student_id = ?
                AND status = 'issued'

                LIMIT 1

            ");

            $check_tc->execute([

                $school_id,
                $current_session_id,
                $student_id

            ]);

            if ($check_tc->fetch()) {

                $message = '

                    <div class="alert alert-warning">

                        TC already generated for this student!

                    </div>

                ';
            }

            else {

                // ==================================================
                // GENERATE TC NUMBER
                // ==================================================

                $year = date('Y');

                $stmt = $pdo->prepare("

                    SELECT COUNT(*)

                    FROM tc_certificates

                    WHERE school_id = ?
                    AND session_id = ?
                    AND tc_no LIKE ?

                ");

                $stmt->execute([

                    $school_id,
                    $current_session_id,
                    "TC-$year%"

                ]);

                $count = $stmt->fetchColumn() + 1;

                $tc_no =
                    "TC-$year/"
                    .
                    str_pad($count, 3, '0', STR_PAD_LEFT);


                // ==================================================
                // INSERT TC
                // ==================================================

                $stmt = $pdo->prepare("

                    INSERT INTO tc_certificates
                    (
                        school_id,
                        session_id,
                        student_id,
                        tc_no,
                        issue_date,
                        reason,
                        status
                    )

                    VALUES
                    (
                        ?, ?, ?, ?, CURDATE(), ?, ?
                    )

                ");

                $stmt->execute([

                    $school_id,
                    $current_session_id,
                    $student_id,
                    $tc_no,
                    'School Transfer',
                    'issued'

                ]);


                $tc_id = $pdo->lastInsertId();


                // ==================================================
                // OPTIONAL STATUS UPDATE
                // ==================================================

                $update_status = $pdo->prepare("

                    UPDATE student_sessions

                    SET status = 'TC'

                    WHERE student_id = ?
                    AND school_id = ?
                    AND session_id = ?

                ");

                $update_status->execute([

                    $student_id,
                    $school_id,
                    $current_session_id

                ]);


                // ==================================================
                // AUDIT LOG
                // ==================================================

                logActivity($pdo, [

                    'school_id' => $school_id,

                    'user_id' => $_SESSION['user_id'],

                    'module' => 'TC Certificates',

                    'action' => 'CREATE',

                    'record_id' => $tc_id,

                    'message' => "TC generated for student {$student['name']}",

                    'old_data' => null,

                    'new_data' => [

                        'student_id' => $student_id,

                        'tc_no' => $tc_no,

                        'issue_date' => date('Y-m-d'),

                        'reason' => 'School Transfer',

                        'status' => 'issued'

                    ]

                ]);


                // ==================================================
                // SUCCESS MESSAGE
                // ==================================================

                $message = '

                    <div class="alert alert-success">

                        TC Generated Successfully!

                        No:

                        <strong>' . htmlspecialchars($tc_no) . '</strong>

                        <a
                            href="tc_print.php?id=' . $tc_id . '"
                            target="_blank"
                            class="btn btn-sm btn-success ml-2"
                        >

                            🖨️ Print TC

                        </a>

                    </div>

                ';
            }
        }
    }
}


// ======================================================
// LOAD CLASSES
// ======================================================

$stmt = $pdo->prepare("

    SELECT

        id,
        class_name

    FROM classes

    WHERE school_id = ?

    ORDER BY id ASC

");

$stmt->execute([$school_id]);

$classes = $stmt->fetchAll(PDO::FETCH_ASSOC);


// ======================================================
// LOAD STUDENTS
// ======================================================

if (!empty($_POST['class_id'])) {

    $stmt = $pdo->prepare("

        SELECT

            s.id,
            s.name,
            ss.roll_no

        FROM student_sessions ss

        INNER JOIN students s
            ON ss.student_id = s.id

        WHERE ss.class_id = ?
        AND ss.school_id = ?
        AND ss.session_id = ?
        AND ss.status = 'Active'

        ORDER BY ss.roll_no ASC

    ");

    $stmt->execute([

        (int)$_POST['class_id'],
        $school_id,
        $current_session_id

    ]);

    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
}


// ======================================================
// PAGE LOAD
// ======================================================

$page_title = 'Generate TC';

include __DIR__ . '/../include/header.php';

include __DIR__ . '/../include/sidebar.php';

?>

<div class="content-wrapper">

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-2">

                <div class="col-sm-6">

                    <h1>

                        <i class="fas fa-file-alt"></i>
                        Generate Transfer Certificate

                    </h1>

                </div>

            </div>

        </div>

    </section>



    <section class="content">

        <div class="container-fluid">

            <div class="row">

                <!-- ====================================================== -->
                <!-- FORM -->
                <!-- ====================================================== -->

                <div class="col-md-8">

                    <div class="card card-primary">

                        <div class="card-header">

                            <h3 class="card-title">

                                Quick TC Generation

                            </h3>

                        </div>



                        <form method="POST">

                            <?= $message ?>



                            <div class="card-body">

                                <div class="row">

                                    <!-- CLASS -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                <i class="fas fa-school"></i>
                                                Select Class

                                            </label>

                                            <select
                                                name="class_id"
                                                class="form-control"
                                                onchange="this.form.submit()"
                                                required
                                            >

                                                <option value="">

                                                    Choose Class

                                                </option>

                                                <?php foreach ($classes as $class): ?>

                                                    <option
                                                        value="<?= $class['id']; ?>"
                                                        <?= ($_POST['class_id'] ?? '') == $class['id'] ? 'selected' : ''; ?>
                                                    >

                                                        <?= htmlspecialchars($class['class_name']); ?>

                                                    </option>

                                                <?php endforeach; ?>

                                            </select>

                                        </div>

                                    </div>



                                    <!-- STUDENT -->

                                    <?php if (!empty($students)): ?>

                                        <div class="col-md-6">

                                            <div class="form-group">

                                                <label>

                                                    <i class="fas fa-user-graduate"></i>
                                                    Select Student

                                                </label>

                                                <select
                                                    name="student_id"
                                                    class="form-control"
                                                    required
                                                >

                                                    <option value="">

                                                        Choose Student

                                                    </option>

                                                    <?php foreach ($students as $student): ?>

                                                        <option value="<?= $student['id']; ?>">

                                                            <?= htmlspecialchars($student['roll_no'] . ' - ' . $student['name']); ?>

                                                        </option>

                                                    <?php endforeach; ?>

                                                </select>

                                            </div>

                                        </div>

                                    <?php endif; ?>

                                </div>

                            </div>



                            <?php if (!empty($students)): ?>

                                <div class="card-footer">

                                    <button
                                        type="submit"
                                        class="btn btn-primary btn-lg"
                                    >

                                        <i class="fas fa-magic"></i>
                                        Generate TC Automatically

                                    </button>

                                </div>

                            <?php endif; ?>

                        </form>

                    </div>

                </div>



                <!-- ====================================================== -->
                <!-- INFO CARD -->
                <!-- ====================================================== -->

                <div class="col-md-4">

                    <div class="card card-info">

                        <div class="card-header">

                            <h3 class="card-title">

                                How it works?

                            </h3>

                        </div>



                        <div class="card-body">

                            <ol>

                                <li>1️⃣ Select Class</li>

                                <li>2️⃣ Students auto-load</li>

                                <li>3️⃣ Select Student</li>

                                <li>4️⃣ Click Generate</li>

                                <li>5️⃣ <strong>TC Ready!</strong> 📄</li>

                            </ol>

                            <hr>

                            <strong>

                                TC Format:

                            </strong>

                            TC-2026/001

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

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