<?php

require_once __DIR__ . '/../library/auth.php'; 
require_once __DIR__ . '/../library/audit_log.php';
$school_id = $_SESSION['school_id'];
allow_roles(['admin', 'accountant']);

// ======================================================
// HANDLE FORM ACTIONS
// ======================================================

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

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

    // ==========================================
    // ADD FEES
    // ==========================================

    if (isset($_POST['add'])) {

        $stmt = $pdo->prepare("
            INSERT INTO class_fees
            (
                school_id,
                class_id,
                total_fees,
                created_at
            )
            VALUES (?, ?, ?, NOW())
        ");

        $stmt->execute([
            $school_id,
            $class_id,
            $total_fees
        ]);
		// ======================================================
// ✅ AUDIT LOG
// ======================================================

$fees_id = $pdo->lastInsertId();

logActivity($pdo, [

    'school_id' => $school_id,

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

    'module' => 'Fees',

    'action' => 'CREATE',

    'record_id' => $fees_id,

    'message' => 'Class fees added',

    'new_data' => [

        'class_id' => $class_id,

        'total_fees' => $total_fees

    ]

]);

        header("Location: total_fees.php?msg=Class fees added successfully");
        exit;
    }

    // ==========================================
    // EDIT FEES
    // ==========================================

    if (isset($_POST['edit'])) {

        $id = (int)($_POST['edit_id'] ?? 0);
		// ======================================================
// ✅ FETCH OLD DATA
// ======================================================

$oldStmt = $pdo->prepare("
    SELECT *
    FROM class_fees
    WHERE id = ?
    AND school_id = ?
");

$oldStmt->execute([
    $id,
    $school_id
]);

$oldData = $oldStmt->fetch(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("
            UPDATE class_fees

            SET
                class_id = ?,
                total_fees = ?

            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([
            $class_id,
            $total_fees,
            $id,
            $school_id
        ]);
		// ======================================================
// ✅ AUDIT LOG
// ======================================================

logActivity($pdo, [

    'school_id' => $school_id,

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

    'module' => 'Fees',

    'action' => 'UPDATE',

    'record_id' => $id,

    'message' => 'Class fees updated',

    'old_data' => [

        'class_id' => $oldData['class_id'] ?? '',

        'total_fees' => $oldData['total_fees'] ?? ''

    ],

    'new_data' => [

        'class_id' => $class_id,

        'total_fees' => $total_fees

    ]

]);

        header("Location: total_fees.php?msg=Class fees updated successfully");
        exit;
    }

    // ==========================================
    // DELETE FEES
    // ==========================================

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

        $id = (int)($_POST['delete_id'] ?? 0);
		// ======================================================
// ✅ FETCH OLD DATA
// ======================================================

$oldStmt = $pdo->prepare("
    SELECT *
    FROM class_fees
    WHERE id = ?
    AND school_id = ?
");

$oldStmt->execute([
    $id,
    $school_id
]);

$oldData = $oldStmt->fetch(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("
            DELETE FROM class_fees
            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([
            $id,
            $school_id
        ]);
		// ======================================================
// ✅ AUDIT LOG
// ======================================================

logActivity($pdo, [

    'school_id' => $school_id,

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

    'module' => 'Fees',

    'action' => 'DELETE',

    'record_id' => $id,

    'message' => 'Class fees deleted',

    'old_data' => [

        'class_id' => $oldData['class_id'] ?? '',

        'total_fees' => $oldData['total_fees'] ?? ''

    ]

]);

        header("Location: total_fees.php?msg=Class fees deleted successfully");
        exit;
    }
}

// ======================================================
// FETCH CLASSES
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        id,
        class_name,
        section

    FROM classes

    WHERE school_id = ?

    ORDER BY class_name, section
");

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

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

// ======================================================
// FETCH CLASS FEES
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        cf.*,

        c.class_name,
        c.section

    FROM class_fees cf

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

    WHERE cf.school_id = ?

    ORDER BY c.class_name, c.section
");

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

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

$page_title = 'Class Total Fees';

require_once __DIR__ . '/../include/header.php';
require_once __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-coins text-warning"></i>

                        Class Total Fees

                    </h1>

                </div>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <!-- MESSAGE -->

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

                <div class="alert alert-success">

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

                </div>

            <?php endif; ?>

            <!-- ADD FORM -->

            <div class="card card-primary card-outline">

                <div class="card-header">

                    <h3 class="card-title">

                        Add Class Fees

                    </h3>

                </div>

                <form method="POST">

                    <div class="card-body">

                        <div class="row">

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

                                <div class="form-group">

                                    <label>Select Class</label>

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

                                        <option value="">
                                            -- Select Class --
                                        </option>

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

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

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

                                                -

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

                                            </option>

                                        <?php endforeach; ?>

                                    </select>

                                </div>

                            </div>

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

                                <div class="form-group">

                                    <label>Total Fees</label>

                                    <input
                                        type="number"
                                        name="total_fees"
                                        class="form-control"
                                        step="0.01"
                                        min="0"
                                        required
                                    >

                                </div>

                            </div>

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

                                <div class="form-group">

                                    <label>&nbsp;</label>

                                    <button
                                        type="submit"
                                        name="add"
                                        class="btn btn-primary btn-block"
                                    >

                                        Add Fees

                                    </button>

                                </div>

                            </div>

                        </div>

                    </div>

                </form>

            </div>

            <!-- TABLE -->

            <div class="card">

                <div class="card-header bg-success text-white">

                    <h3 class="card-title">

                        All Class Fees
                        (<?= count($class_fees) ?>)

                    </h3>

                </div>

                <div class="card-body">

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

                        <div class="text-center text-muted p-5">

                            No class fees found

                        </div>

                    <?php else: ?>

                        <div class="table-responsive">

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

                                <thead>

                                    <tr>

                                        <th>#</th>
                                        <th>Class</th>
                                        <th>Total Fees</th>
                                        <th>Created</th>
                                        <th>Actions</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php foreach ($class_fees as $index => $fee): ?>

                                        <tr>

                                            <td>
                                                <?= $index + 1 ?>
                                            </td>

                                            <td>

                                                <strong>

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

                                                    -

                                                    <?= htmlspecialchars($fee['section']) ?>

                                                </strong>

                                            </td>

                                            <td>

                                                ₹<?= number_format($fee['total_fees'], 2) ?>

                                            </td>

                                            <td>

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

                                            </td>

                                            <td>

                                                <!-- EDIT -->

                                                <button
                                                    class="btn btn-warning btn-sm edit-fee"
                                                    data-id="<?= $fee['id'] ?>"
                                                    data-class="<?= $fee['class_id'] ?>"
                                                    data-fees="<?= $fee['total_fees'] ?>"
                                                >

                                                    Edit

                                                </button>

                                                <!-- DELETE -->

                                                <form
                                                    method="POST"
                                                    style="display:inline-block;"
                                                    onsubmit="return confirm('Delete this fee structure?')"
                                                >

                                                    <input
                                                        type="hidden"
                                                        name="delete_id"
                                                        value="<?= $fee['id'] ?>"
                                                    >

                                                    <button
                                                        type="submit"
                                                        name="delete"
                                                        class="btn btn-danger btn-sm"
                                                    >

                                                        Delete

                                                    </button>

                                                </form>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>

                        </div>

                    <?php endif; ?>

                </div>

            </div>

        </div>

    </section>

</div>

<!-- EDIT MODAL -->

<div class="modal fade" id="editModal">

    <div class="modal-dialog">

        <div class="modal-content">

            <form method="POST">

                <div class="modal-header">

                    <h5 class="modal-title">

                        Edit Class Fees

                    </h5>

                    <button
                        type="button"
                        class="close"
                        data-dismiss="modal"
                    >
                        &times;
                    </button>

                </div>

                <div class="modal-body">

                    <input
                        type="hidden"
                        name="edit_id"
                        id="edit_id"
                    >

                    <div class="form-group">

                        <label>Class</label>

                        <select
                            name="class_id"
                            id="edit_class_id"
                            class="form-control"
                            required
                        >

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

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

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

                                    -

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

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                    <div class="form-group">

                        <label>Total Fees</label>

                        <input
                            type="number"
                            name="total_fees"
                            id="edit_total_fees"
                            class="form-control"
                            step="0.01"
                            min="0"
                            required
                        >

                    </div>

                </div>

                <div class="modal-footer">

                    <button
                        type="submit"
                        name="edit"
                        class="btn btn-success"
                    >

                        Update

                    </button>

                </div>

            </form>

        </div>

    </div>

</div>

<script>

document.querySelectorAll('.edit-fee').forEach(button => {

    button.addEventListener('click', function () {

        document.getElementById('edit_id').value =
            this.dataset.id;

        document.getElementById('edit_class_id').value =
            this.dataset.class;

        document.getElementById('edit_total_fees').value =
            this.dataset.fees;

        $('#editModal').modal('show');
    });

});

</script>

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