<?php

ob_start();

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

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

$school_id          = $_SESSION['school_id'];
$current_session_id = get_current_session_id($pdo);



// ======================================================
// AJAX : STUDENT DETAILS
// ======================================================

if (
    isset($_GET['action']) &&
    $_GET['action'] === 'student_details'
) {

    header('Content-Type: application/json');

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

    if ($student_id <= 0) {

        echo json_encode([]);

        exit;
    }

    $stmt = $pdo->prepare("
        SELECT

            s.id,
            s.name,

            ss.roll_no,
            ss.section,

            c.class_name,

            sp.father_name,
            sp.father_phone

        FROM student_sessions ss

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

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

        LEFT JOIN student_parents sp
            ON sp.student_id = s.id
            AND sp.school_id = ss.school_id
            AND sp.session_id = ss.session_id

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

        LIMIT 1
    ");

    $stmt->execute([

        $student_id,
        $school_id,
        $current_session_id

    ]);

    echo json_encode(
        $stmt->fetch(PDO::FETCH_ASSOC) ?: []
    );

    exit;
}

// ======================================================
// AJAX : LOAD STUDENTS
// ======================================================

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'load_students'
) {

    header('Content-Type: application/json');

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

    if ($class_id <= 0) {

        echo json_encode([]);

        exit;
    }

    $verify = $pdo->prepare("
        SELECT id
        FROM classes
        WHERE id = ?
        AND school_id = ?
        LIMIT 1
    ");

    $verify->execute([

        $class_id,
        $school_id

    ]);

    if (!$verify->fetch()) {

        echo json_encode([]);

        exit;
    }

    $stmt = $pdo->prepare("
        SELECT

            s.id,
            s.name,

            ss.roll_no,
            ss.section,

            c.class_name

        FROM student_sessions ss

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

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

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

        ORDER BY
            ss.roll_no + 0 ASC,
            s.name ASC
    ");

    $stmt->execute([

        $class_id,
        $school_id,
        $current_session_id

    ]);

    echo json_encode(
        $stmt->fetchAll(PDO::FETCH_ASSOC)
    );

    exit;
}

// ======================================================
// SAVE RECEIPT
// ======================================================

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['save_receipt'])
) {

    try {

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

        $paid_amount = (float) ($_POST['paid_amount'] ?? 0);

        $payment_mode = trim(
            $_POST['payment_mode'] ?? 'Cash'
        );

        $payment_date = trim(
            $_POST['payment_date'] ?? date('Y-m-d')
        );

        $allowed_modes = [

            'Cash',
            'UPI',
            'Card',
            'Cheque'

        ];

        if ($student_id <= 0) {

            throw new Exception(
                'Invalid student selected.'
            );
        }

        if ($paid_amount <= 0) {

            throw new Exception(
                'Amount must be greater than zero.'
            );
        }

        if (
            !in_array(
                $payment_mode,
                $allowed_modes,
                true
            )
        ) {

            throw new Exception(
                'Invalid payment mode.'
            );
        }

        if (
            !preg_match(
                '/^\d{4}-\d{2}-\d{2}$/',
                $payment_date
            )
        ) {

            throw new Exception(
                'Invalid payment date.'
            );
        }

        $stmt = $pdo->prepare("
            SELECT id
            FROM student_sessions

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

            LIMIT 1
        ");

        $stmt->execute([

            $student_id,
            $school_id,
            $current_session_id

        ]);

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

        if (!$student_session) {

            throw new Exception(
                'Student session not found.'
            );
        }

        $pdo->beginTransaction();

        // ==================================================
        // ENSURE RECEIPT SETTINGS
        // ==================================================

        $stmt = $pdo->prepare("
            SELECT id
            FROM receipt_settings
            WHERE school_id = ?
            LIMIT 1
        ");

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

        if (!$stmt->fetch()) {

            $insert = $pdo->prepare("
                INSERT INTO receipt_settings
                (
                    school_id,
                    prefix,
                    next_number,
                    padding,
                    default_mode
                )

                VALUES
                (
                    ?, 'REC', 1, 4, 'Cash'
                )
            ");

            $insert->execute([$school_id]);
        }

        // ==================================================
        // LOCK SETTINGS ROW
        // ==================================================

        $stmt = $pdo->prepare("
            SELECT

                prefix,
                next_number,
                padding

            FROM receipt_settings

            WHERE school_id = ?

            FOR UPDATE
        ");

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

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

        if (!$settings) {

            throw new Exception(
                'Receipt settings missing.'
            );
        }

        $receipt_no =
            strtoupper($settings['prefix'])
            . '-'
            . str_pad(

                $settings['next_number'],

                $settings['padding'],

                '0',

                STR_PAD_LEFT

            );

        // ==================================================
        // INSERT PAYMENT
        // ==================================================

        $stmt = $pdo->prepare("
            INSERT INTO fee_payments
            (
                school_id,
                session_id,
                student_id,
                paid_amount,
                payment_mode,
                payment_date,
                receipt_no
            )

            VALUES
            (
                ?, ?, ?, ?, ?, ?, ?
            )
        ");

        $stmt->execute([

            $school_id,

            $current_session_id,

            $student_id,

            $paid_amount,

            $payment_mode,

            $payment_date,

            $receipt_no

        ]);

        $payment_id = $pdo->lastInsertId();

        // ==================================================
        // UPDATE NEXT NUMBER
        // ==================================================

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

            SET next_number = next_number + 1

            WHERE school_id = ?
        ");

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

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Fees',

            'action' => 'PAYMENT',

            'record_id' => $payment_id,

            'message' =>
                "Fee payment created : {$receipt_no}"

        ]);

        $pdo->commit();

        header(
            'Location: print_receipt.php?receipt_no='
            . urlencode($receipt_no)
        );

        exit;

    } catch (Exception $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }

        header(
            'Location: add_fees.php?msg='
            . urlencode($e->getMessage())
        );

        exit;
    }
}
$page_title = 'Add Fees Receipt';

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

?>

<div class="content-wrapper">

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

    <section class="content-header">

        <div class="container-fluid">

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

                <div class="mb-2 mb-md-0">

                    <h1 class="m-0">

                        <i class="fas fa-money-check-alt text-success"></i>

                        Add Fees Receipt

                    </h1>

                    <small class="text-muted">

                        Create secure fee receipts

                    </small>

                </div>

            </div>

        </div>

    </section>

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

    <section class="content">

        <div class="container-fluid">

            <!-- ALERT -->

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

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

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

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

                </div>

            <?php endif; ?>

            <!-- ============================================== -->
            <!-- CLASS FILTER -->
            <!-- ============================================== -->

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

                <div class="card-header">

                    <h3 class="card-title">

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

                        Select Class

                    </h3>

                </div>

                <div class="card-body">

                    <div class="row align-items-end">

                        <div class="col-12 col-md-8 mb-3 mb-md-0">

                            <label class="font-weight-bold">

                                Class *

                            </label>

                            <select
                                id="class_id"
                                class="form-control"
                            >

                                <option value="">

                                    Select Class

                                </option>

                                <?php

                                $stmt = $pdo->prepare("
                                    SELECT

                                        id,
                                        class_name

                                    FROM classes

                                    WHERE school_id = ?

                                    ORDER BY class_name ASC
                                ");

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

                                while ($row = $stmt->fetch()) :

                                ?>

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

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

                                    </option>

                                <?php endwhile; ?>

                            </select>

                        </div>

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

                            <button
                                type="button"
                                id="loadBtn"
                                onclick="loadStudents()"
                                class="btn btn-primary btn-block"
                            >

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

                                Load Students

                            </button>

                        </div>

                    </div>

                </div>

            </div>

            <!-- ============================================== -->
            <!-- STUDENTS -->
            <!-- ============================================== -->

            <div
                id="studentsWrapper"
                class="mt-4"
                style="display:none;"
            >

                <!-- DESKTOP -->

                <div class="card card-outline card-success shadow-sm d-none d-md-block">

                    <div class="card-header">

                        <h3 class="card-title">

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

                            Students List

                        </h3>

                    </div>

                    <div class="card-body p-0">

                        <div class="table-responsive">

                            <table class="table table-hover mb-0">

                                <thead class="thead-light">

                                    <tr>

                                        <th>Roll</th>
                                        <th>Name</th>
                                        <th>Class</th>
                                        <th>Section</th>
                                        <th width="120">

                                            Action

                                        </th>

                                    </tr>

                                </thead>

                                <tbody id="studentsTableBody">

                                </tbody>

                            </table>

                        </div>

                    </div>

                </div>

                <!-- MOBILE -->

                <div
                    id="mobileStudentCards"
                    class="d-block d-md-none"
                >

                </div>

            </div>

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

            <form
                method="post"
                id="paymentForm"
                style="display:none;"
            >

                <div class="card card-outline card-warning shadow-sm mt-4">

                    <div class="card-header">

                        <h3 class="card-title">

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

                            Payment Details

                        </h3>

                    </div>

                    <div class="card-body">

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

                        <!-- STUDENT INFO -->

                        <div class="row">

                            <div class="col-12 col-md-6 col-lg-3 mb-3">

                                <label>Name</label>

                                <input
                                    type="text"
                                    id="student_name"
                                    class="form-control"
                                    readonly
                                >

                            </div>

                            <div class="col-12 col-md-6 col-lg-2 mb-3">

                                <label>Roll No</label>

                                <input
                                    type="text"
                                    id="student_roll"
                                    class="form-control"
                                    readonly
                                >

                            </div>

                            <div class="col-12 col-md-6 col-lg-3 mb-3">

                                <label>Father Name</label>

                                <input
                                    type="text"
                                    id="father_name"
                                    class="form-control"
                                    readonly
                                >

                            </div>

                            <div class="col-12 col-md-6 col-lg-2 mb-3">

                                <label>Phone</label>

                                <input
                                    type="text"
                                    id="student_phone"
                                    class="form-control"
                                    readonly
                                >

                            </div>

                            <div class="col-12 col-md-6 col-lg-2 mb-3">

                                <label>Class</label>

                                <input
                                    type="text"
                                    id="student_class"
                                    class="form-control"
                                    readonly
                                >

                            </div>

                        </div>

                        <hr>

                        <!-- PAYMENT DETAILS -->

                        <div class="row">

                            <div class="col-12 col-md-6 col-lg-4 mb-3">

                                <label>

                                    Amount (₹) *

                                </label>

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

                            </div>

                            <div class="col-12 col-md-6 col-lg-4 mb-3">

                                <label>

                                    Payment Mode *

                                </label>

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

                                    <option value="">

                                        Select Mode

                                    </option>

                                    <option value="Cash">

                                        💵 Cash

                                    </option>

                                    <option value="UPI">

                                        📱 UPI

                                    </option>

                                    <option value="Card">

                                        💳 Card

                                    </option>

                                    <option value="Cheque">

                                        🧾 Cheque

                                    </option>

                                </select>

                            </div>

                            <div class="col-12 col-md-6 col-lg-4 mb-3">

                                <label>

                                    Payment Date *

                                </label>

                                <input
                                    type="date"
                                    name="payment_date"
                                    class="form-control"
                                    value="<?= date('Y-m-d') ?>"
                                    required
                                >

                            </div>

                        </div>

                    </div>

                    <div class="card-footer">

                        <div class="d-flex flex-column flex-md-row justify-content-end">

                            <button
                                type="button"
                                onclick="resetForm()"
                                class="btn btn-secondary mb-2 mb-md-0 mr-md-2"
                            >

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

                                Cancel

                            </button>

                            <button
                                type="submit"
                                name="save_receipt"
                                id="saveBtn"
                                class="btn btn-success"
                            >

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

                                Save Receipt

                            </button>

                        </div>

                    </div>

                </div>

            </form>

        </div>

    </section>

</div>

<!-- ====================================================== -->
<!-- JAVASCRIPT -->
<!-- ====================================================== -->

<script>

function loadStudents() {

    let classId = $('#class_id').val();

    if (!classId) {

        alert('Please select class.');

        return;
    }

    $('#loadBtn')
        .prop('disabled', true)
        .html(
            '<i class="fas fa-spinner fa-spin"></i> Loading...'
        );

    $('#studentsWrapper').show();

    $('#studentsTableBody').html(`
        <tr>
            <td colspan="5" class="text-center p-4">
                <i class="fas fa-spinner fa-spin"></i>
                Loading students...
            </td>
        </tr>
    `);

    $.post(

        '',

        {
            action : 'load_students',
            class_id : classId
        },

        function(response) {

            let desktopHtml = '';
            let mobileHtml  = '';

            if (response.length === 0) {

                desktopHtml = `
                    <tr>
                        <td colspan="5" class="text-center p-4">
                            No students found
                        </td>
                    </tr>
                `;

                mobileHtml = `
                    <div class="alert alert-warning">
                        No students found
                    </div>
                `;

            } else {

                response.forEach(student => {

                    desktopHtml += `
                        <tr>

                            <td>
                                <strong>
                                    ${student.roll_no ?? '-'}
                                </strong>
                            </td>

                            <td>
                                ${student.name}
                            </td>

                            <td>
                                ${student.class_name}
                            </td>

                            <td>
                                ${student.section ?? '-'}
                            </td>

                            <td>

                                <button
                                    type="button"
                                    class="btn btn-sm btn-primary"
                                    onclick="selectStudent(${student.id})"
                                >

                                    Select

                                </button>

                            </td>

                        </tr>
                    `;

                    mobileHtml += `
                        <div class="card shadow-sm mb-3 border-0">

                            <div class="card-body">

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

                                    <div>

                                        <h6 class="font-weight-bold mb-1">

                                            ${student.name}

                                        </h6>

                                        <small class="text-muted">

                                            Roll :
                                            ${student.roll_no ?? '-'}

                                        </small>

                                    </div>

                                    <span class="badge badge-info">

                                        ${student.section ?? '-'}

                                    </span>

                                </div>

                                <hr>

                                <button
                                    type="button"
                                    class="btn btn-primary btn-block"
                                    onclick="selectStudent(${student.id})"
                                >

                                    Select Student

                                </button>

                            </div>

                        </div>
                    `;
                });
            }

            $('#studentsTableBody').html(desktopHtml);

            $('#mobileStudentCards').html(mobileHtml);

            $('#loadBtn')
                .prop('disabled', false)
                .html(
                    '<i class="fas fa-search"></i> Load Students'
                );

        },

        'json'

    ).fail(function() {

        alert('Failed to load students.');

        $('#loadBtn')
            .prop('disabled', false)
            .html(
                '<i class="fas fa-search"></i> Load Students'
            );

    });
}

function selectStudent(studentId) {
	 $('#paymentForm')[0].reset();

    $('#student_id').val('');
    $('#student_name').val('');
    $('#student_roll').val('');
    $('#father_name').val('');
    $('#student_phone').val('');
    $('#student_class').val('');

    $.get(

        '?action=student_details&student_id=' + studentId,

        function(data) {

            if (!data.id) {

                alert('Student not found.');

                return;
            }

            $('#student_id').val(data.id);

            $('#student_name').val(data.name);

            $('#student_roll').val(data.roll_no ?? '');

            $('#father_name').val(data.father_name ?? '');

            $('#student_phone').val(data.father_phone ?? '');

            $('#student_class').val(
                data.class_name + ' - ' + (data.section ?? '')
            );

            $('#paymentForm').slideDown();

            $('html, body').animate({

                scrollTop:
                    $('#paymentForm').offset().top - 70

            }, 500);

        },

        'json'

    ).fail(function() {

        alert('Failed to load student.');

    });
}

function resetForm() {

    $('#paymentForm').hide();

    $('#paymentForm')[0].reset();

    $('#student_id').val('');
}

$('#paymentForm').on('submit', function() {

    $('#saveBtn')
        .prop('disabled', true)
        .html(
            '<i class="fas fa-spinner fa-spin"></i> Saving...'
        );
});
</script>

<?php

require_once __DIR__ . '/../include/footer.php';

ob_end_flush();

?>