<?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']);


// ======================================================
// DELETE TC
// ======================================================

if (isset($_GET['delete'])) {

    $tc_id = intval($_GET['delete']);


    // ==================================================
    // FETCH OLD DATA
    // ==================================================

    $check_stmt = $pdo->prepare("

        SELECT

            tc.id,
            tc.tc_no,
            s.name AS student_name

        FROM tc_certificates tc

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

        WHERE tc.id = ?
        AND tc.school_id = ?
        AND tc.session_id = ?

        LIMIT 1

    ");

    $check_stmt->execute([

        $tc_id,
        $school_id,
        $current_session_id

    ]);

    $old_data = $check_stmt->fetch(PDO::FETCH_ASSOC);


    // ==================================================
    // INVALID RECORD
    // ==================================================

    if (!$old_data) {

        header("Location: tc_list.php?msg=❌ TC Not Found!");

        exit;
    }


    // ==================================================
    // DELETE TC
    // ==================================================

    $delete_stmt = $pdo->prepare("

        DELETE FROM tc_certificates

        WHERE id = ?
        AND school_id = ?

    ");

    $delete_stmt->execute([

        $tc_id,
        $school_id

    ]);


    // ==================================================
    // UPDATE STUDENT STATUS BACK
    // ==================================================

    $status_stmt = $pdo->prepare("

        UPDATE student_sessions

        SET status = 'Active'

        WHERE student_id = (
            SELECT student_id
            FROM tc_certificates
            WHERE id = ?
            LIMIT 1
        )

        AND school_id = ?
        AND session_id = ?

    ");

    $status_stmt->execute([

        $tc_id,
        $school_id,
        $current_session_id

    ]);


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

    logActivity($pdo, [

        'school_id' => $school_id,

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

        'module'    => 'TC Certificates',

        'action'    => 'DELETE',

        'record_id' => $tc_id,

        'message'   => "TC deleted for student {$old_data['student_name']}",

        'old_data'  => $old_data,

        'new_data'  => null

    ]);


    header("Location: tc_list.php?msg=✅ TC Deleted Successfully!");

    exit;
}


// ======================================================
// FETCH TC LIST
// ======================================================

$query = "

    SELECT

        tc.*,

        s.name,

        ss.roll_no,
        ss.admission_no,

        c.class_name

    FROM tc_certificates tc

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

    LEFT JOIN student_sessions ss
        ON ss.student_id = s.id
        AND ss.session_id = tc.session_id

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

    WHERE tc.school_id = ?
    AND tc.session_id = ?

    ORDER BY tc.created_at DESC

";

$stmt = $pdo->prepare($query);

$stmt->execute([

    $school_id,
    $current_session_id

]);

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

$total_tcs = count($tcs);


// ======================================================
// PAGE
// ======================================================

$page_title = 'TC List';

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

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

?>

<div class="content-wrapper">

    <!-- ====================================================== -->
    <!-- PAGE HEADER -->
    <!-- ====================================================== -->

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-3">

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

                    <h1>

                        <i class="fas fa-certificate text-primary"></i>

                        Transfer Certificates

                    </h1>

                </div>

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

                    <a
                        href="tc_generate.php"
                        class="btn btn-success"
                    >

                        <i class="fas fa-plus-circle"></i>

                        Generate New TC

                    </a>

                </div>

            </div>

        </div>

    </section>


    <!-- ====================================================== -->
    <!-- CONTENT -->
    <!-- ====================================================== -->

    <section class="content">

        <div class="container-fluid">


            <!-- ====================================================== -->
            <!-- MESSAGE -->
            <!-- ====================================================== -->

            <?php if (isset($_GET['msg'])): ?>

                <div class="alert alert-success alert-dismissible fade show">

                    <i class="fas fa-check-circle mr-2"></i>

                    <?= htmlspecialchars($_GET['msg']) ?>

                    <button
                        type="button"
                        class="close"
                        data-dismiss="alert"
                    >

                        &times;

                    </button>

                </div>

            <?php endif; ?>


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

            <div class="card shadow-lg border-0">

                <div class="card-header bg-primary">

                    <div class="d-flex justify-content-between align-items-center">

                        <h3 class="card-title text-white mb-0">

                            <i class="fas fa-list"></i>

                            Generated TC Records

                        </h3>

                        <span class="badge badge-light p-2">

                            Total:
                            <?= $total_tcs ?>

                        </span>

                    </div>

                </div>


                <!-- ====================================================== -->
                <!-- EMPTY -->
                <!-- ====================================================== -->

                <?php if (empty($tcs)): ?>

                    <div class="card-body text-center p-5">

                        <i class="fas fa-file-alt fa-4x text-muted mb-4"></i>

                        <h4 class="text-muted mb-3">

                            No Transfer Certificates Found

                        </h4>

                        <a
                            href="tc_generate.php"
                            class="btn btn-primary"
                        >

                            <i class="fas fa-plus-circle"></i>

                            Generate First TC

                        </a>

                    </div>

                <?php else: ?>

                    <!-- ====================================================== -->
                    <!-- TABLE -->
                    <!-- ====================================================== -->

                    <div class="card-body">

                        <div class="table-responsive">

                            <table class="table table-bordered table-hover">

                                <thead class="thead-dark">

                                    <tr>

                                        <th>#</th>

                                        <th>TC No</th>

                                        <th>Student Details</th>

                                        <th>Class</th>

                                        <th>Issue Date</th>

                                        <th>Status</th>

                                        <th width="170">Actions</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php foreach ($tcs as $index => $row): ?>

                                        <tr>

                                            <td>

                                                <?= $index + 1 ?>

                                            </td>

                                            <td>

                                                <strong class="text-primary">

                                                    <?= htmlspecialchars($row['tc_no']) ?>

                                                </strong>

                                            </td>

                                            <td>

                                                <strong>

                                                    <?= htmlspecialchars($row['name']) ?>

                                                </strong>

                                                <br>

                                                <small class="text-muted">

                                                    Roll:
                                                    <?= htmlspecialchars($row['roll_no'] ?? '-') ?>

                                                    |

                                                    Admission:
                                                    <?= htmlspecialchars($row['admission_no'] ?? '-') ?>

                                                </small>

                                            </td>

                                            <td>

                                                <span class="badge badge-info p-2">

                                                    <?= htmlspecialchars($row['class_name'] ?? '-') ?>

                                                </span>

                                            </td>

                                            <td>

                                                <?= date('d M Y', strtotime($row['issue_date'])) ?>

                                            </td>

                                            <td>

                                                <span class="badge badge-success p-2">

                                                    <?= ucfirst($row['status']) ?>

                                                </span>

                                            </td>

                                            <td>

                                                <div class="btn-group btn-group-sm">

                                                    <a
                                                        href="tc_view.php?id=<?= $row['id'] ?>"
                                                        class="btn btn-primary"
                                                        title="View TC"
                                                    >

                                                        <i class="fas fa-eye"></i>

                                                    </a>

                                                    <a
                                                        href="tc_print.php?id=<?= $row['id'] ?>"
                                                        target="_blank"
                                                        class="btn btn-success"
                                                        title="Print TC"
                                                    >

                                                        <i class="fas fa-print"></i>

                                                    </a>

                                                    <button
                                                        type="button"
                                                        onclick="confirmDelete(<?= $row['id'] ?>)"
                                                        class="btn btn-danger"
                                                        title="Delete TC"
                                                    >

                                                        <i class="fas fa-trash"></i>

                                                    </button>

                                                </div>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>

                        </div>

                    </div>

                <?php endif; ?>

            </div>

        </div>

    </section>

</div>


<!-- ====================================================== -->
<!-- DELETE SCRIPT -->
<!-- ====================================================== -->

<script>

function confirmDelete(id) {

    if (confirm('Are you sure you want to delete this TC?')) {

        window.location =
            'tc_list.php?delete=' + id;
    }
}

</script>

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