<?php

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);

$page_title = 'Fees Receipts';

// ======================================================
// DELETE RECEIPT
// ======================================================

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

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

    if ($receipt_id > 0) {

        try {

            $pdo->beginTransaction();

            // ==========================================
            // FETCH RECEIPT
            // ==========================================

            $stmt = $pdo->prepare("
                SELECT

                    receipt_no,
                    paid_amount

                FROM fee_payments

                WHERE id = ?
                AND school_id = ?
                AND session_id = ?

                LIMIT 1
            ");

            $stmt->execute([

                $receipt_id,
                $school_id,
                $current_session_id

            ]);

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

            if (!$receipt) {

                throw new Exception(
                    'Receipt not found.'
                );
            }

            // ==========================================
            // DELETE RECEIPT
            // ==========================================

            $stmt = $pdo->prepare("
                DELETE FROM fee_payments

                WHERE id = ?
                AND school_id = ?
                AND session_id = ?
            ");

            $stmt->execute([

                $receipt_id,
                $school_id,
                $current_session_id

            ]);

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

            logActivity($pdo, [

                'school_id' => $school_id,

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

                'module' => 'Fees',

                'action' => 'DELETE',

                'record_id' => $receipt_id,

                'message' =>
                    "Receipt deleted : {$receipt['receipt_no']}",

                'old_data' => $receipt

            ]);

            $pdo->commit();

            header(
                'Location:view_fees.php?msg=' .
                urlencode('Receipt deleted successfully')
            );

            exit;

        } catch (Exception $e) {

            if ($pdo->inTransaction()) {

                $pdo->rollBack();
            }

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

            exit;
        }
    }
}

// ======================================================
// FILTER DATE
// ======================================================

$filter_date = trim(
    $_GET['date'] ?? date('Y-m-d')
);

// ======================================================
// SUMMARY
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        COUNT(*) AS total_receipts,

        COALESCE(
            SUM(paid_amount),
            0
        ) AS total_collection,

        COUNT(
            CASE
                WHEN payment_mode = 'Cash'
                THEN 1
            END
        ) AS cash_payments,

        COUNT(
            CASE
                WHEN payment_mode = 'UPI'
                THEN 1
            END
        ) AS upi_payments

    FROM fee_payments

    WHERE DATE(payment_date) = ?
    AND school_id = ?
    AND session_id = ?
");

$stmt->execute([

    $filter_date,
    $school_id,
    $current_session_id

]);

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

// ======================================================
// FETCH RECEIPTS
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        fp.id,
        fp.receipt_no,
        fp.paid_amount,
        fp.payment_mode,
        fp.payment_date,

        s.name,

        ss.roll_no,
        ss.section,

        c.class_name

    FROM fee_payments fp

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

    INNER JOIN student_sessions ss
        ON ss.student_id = s.id
        AND ss.session_id = fp.session_id
        AND ss.school_id = fp.school_id

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

    WHERE DATE(fp.payment_date) = ?
    AND fp.school_id = ?
    AND fp.session_id = ?

    ORDER BY fp.id DESC
");

$stmt->execute([

    $filter_date,
    $school_id,
    $current_session_id

]);

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

// ======================================================
// LAST 7 DAYS SUMMARY
// ======================================================

$summary_stmt = $pdo->prepare("
    SELECT

        DATE(payment_date) AS payment_day,

        COUNT(*) AS total_receipts,

        SUM(paid_amount) AS total_amount

    FROM fee_payments

    WHERE school_id = ?
    AND session_id = ?

    GROUP BY DATE(payment_date)

    ORDER BY payment_day DESC

    LIMIT 7
");

$summary_stmt->execute([

    $school_id,
    $current_session_id

]);

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-receipt text-primary"></i>

                        Fees Receipts

                    </h1>

                    <small class="text-muted">

                        Manage all fees collections

                    </small>

                </div>

                <div>

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

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

                        New Receipt

                    </a>

                </div>

            </div>

        </div>

    </section>

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

    <section class="content">

        <div class="container-fluid">

            <!-- ALERT -->

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

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

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

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

                </div>

            <?php endif; ?>

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

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

                <div class="card-header">

                    <h3 class="card-title">

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

                        Filter Receipts

                    </h3>

                </div>

                <div class="card-body">

                    <form method="GET">

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

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

                                <label>

                                    Select Date

                                </label>

                                <input
                                    type="date"
                                    name="date"
                                    value="<?= htmlspecialchars($filter_date) ?>"
                                    class="form-control"
                                    required
                                >

                            </div>

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

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

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

                                    Filter

                                </button>

                                <a
                                    href="view_fees.php"
                                    class="btn btn-secondary"
                                >

                                    Today

                                </a>

                            </div>

                        </div>

                    </form>

                </div>

            </div>

            <!-- ========================================== -->
            <!-- SUMMARY -->
            <!-- ========================================== -->

            <div class="row mt-4">

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

                    <div class="small-box bg-success shadow-sm">

                        <div class="inner">

                            <h3>

                                <?= (int) ($summary['total_receipts'] ?? 0) ?>

                            </h3>

                            <p>

                                Total Receipts

                            </p>

                        </div>

                        <div class="icon">

                            <i class="fas fa-file-invoice"></i>

                        </div>

                    </div>

                </div>

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

                    <div class="small-box bg-primary shadow-sm">

                        <div class="inner">

                            <h3>

                                ₹<?= number_format($summary['total_collection'] ?? 0, 2) ?>

                            </h3>

                            <p>

                                Total Collection

                            </p>

                        </div>

                        <div class="icon">

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

                        </div>

                    </div>

                </div>

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

                    <div class="small-box bg-warning shadow-sm">

                        <div class="inner">

                            <h3>

                                <?= (int) ($summary['cash_payments'] ?? 0) ?>

                            </h3>

                            <p>

                                Cash Payments

                            </p>

                        </div>

                        <div class="icon">

                            <i class="fas fa-money-bill-wave"></i>

                        </div>

                    </div>

                </div>

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

                    <div class="small-box bg-info shadow-sm">

                        <div class="inner">

                            <h3>

                                <?= (int) ($summary['upi_payments'] ?? 0) ?>

                            </h3>

                            <p>

                                UPI Payments

                            </p>

                        </div>

                        <div class="icon">

                            <i class="fas fa-mobile-alt"></i>

                        </div>

                    </div>

                </div>

            </div>

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

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

                <div class="card-header">

                    <h3 class="card-title">

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

                        Receipts List

                    </h3>

                </div>

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

                    <!-- DESKTOP TABLE -->

                    <div class="table-responsive d-none d-md-block">

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

                            <thead class="thead-light">

                                <tr>

                                    <th>Receipt</th>
                                    <th>Student</th>
                                    <th>Class</th>
                                    <th>Amount</th>
                                    <th>Mode</th>
                                    <th>Date</th>
                                    <th width="230">

                                        Actions

                                    </th>

                                </tr>

                            </thead>

                            <tbody>

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

                                    <tr>

                                        <td
                                            colspan="7"
                                            class="text-center p-4 text-muted"
                                        >

                                            No receipts found

                                        </td>

                                    </tr>

                                <?php endif; ?>

                                <?php foreach ($receipts as $r) : ?>

                                    <tr>

                                        <td>

                                            <strong>

                                                <?= htmlspecialchars($r['receipt_no']) ?>

                                            </strong>

                                        </td>

                                        <td>

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

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

                                            </div>

                                            <small class="text-muted">

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

                                            </small>

                                        </td>

                                        <td>

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

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

                                        </td>

                                        <td>

                                            <strong class="text-success">

                                                ₹<?= number_format($r['paid_amount'], 2) ?>

                                            </strong>

                                        </td>

                                        <td>

                                            <span class="badge badge-info">

                                                <?= htmlspecialchars($r['payment_mode']) ?>

                                            </span>

                                        </td>

                                        <td>

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

                                        </td>

                                        <td>

                                            <div class="btn-group">

                                                <a
                                                    href="print_receipt.php?receipt_no=<?= urlencode($r['receipt_no']) ?>"
                                                    target="_blank"
                                                    class="btn btn-sm btn-info"
                                                >

                                                    Print

                                                </a>

                                                <a
                                                    href="edit_fees.php?id=<?= $r['id'] ?>"
                                                    class="btn btn-sm btn-warning"
                                                >

                                                    Edit

                                                </a>

                                                <a
                                                    href="?delete=<?= $r['id'] ?>"
                                                    class="btn btn-sm btn-danger"
                                                    onclick="return confirm('Delete this receipt?')"
                                                >

                                                    Delete

                                                </a>

                                            </div>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                    <!-- MOBILE CARDS -->

                    <div class="d-block d-md-none p-3">

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

                            <div class="alert alert-warning">

                                No receipts found

                            </div>

                        <?php endif; ?>

                        <?php foreach ($receipts as $r) : ?>

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

                                <div class="card-body">

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

                                        <div>

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

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

                                            </h6>

                                            <small class="text-muted">

                                                <?= htmlspecialchars($r['receipt_no']) ?>

                                            </small>

                                        </div>

                                        <span class="badge badge-success">

                                            ₹<?= number_format($r['paid_amount'], 0) ?>

                                        </span>

                                    </div>

                                    <hr>

                                    <div class="small text-muted mb-2">

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

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

                                    </div>

                                    <div class="small mb-3">

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

                                        ·

                                        <?= htmlspecialchars($r['payment_mode']) ?>

                                    </div>

                                    <div class="d-flex">

                                        <a
                                            href="print_receipt.php?receipt_no=<?= urlencode($r['receipt_no']) ?>"
                                            target="_blank"
                                            class="btn btn-info btn-sm flex-fill mr-1"
                                        >

                                            Print

                                        </a>

                                        <a
                                            href="edit_fees.php?id=<?= $r['id'] ?>"
                                            class="btn btn-warning btn-sm flex-fill mr-1"
                                        >

                                            Edit

                                        </a>

                                        <a
                                            href="?delete=<?= $r['id'] ?>"
                                            class="btn btn-danger btn-sm flex-fill"
                                            onclick="return confirm('Delete this receipt?')"
                                        >

                                            Delete

                                        </a>

                                    </div>

                                </div>

                            </div>

                        <?php endforeach; ?>

                    </div>

                </div>

            </div>

            <!-- ========================================== -->
            <!-- LAST 7 DAYS -->
            <!-- ========================================== -->

            <div class="row mt-4">

                <div class="col-12 col-lg-6">

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

                        <div class="card-header">

                            <h3 class="card-title">

                                <i class="fas fa-chart-line"></i>

                                Last 7 Days Summary

                            </h3>

                        </div>

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

                            <ul class="list-group list-group-flush">

                                <?php while ($row = $summary_stmt->fetch(PDO::FETCH_ASSOC)) : ?>

                                    <li class="list-group-item d-flex justify-content-between align-items-center">

                                        <div>

                                            <strong>

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

                                            </strong>

                                        </div>

                                        <div class="text-right">

                                            <div class="font-weight-bold text-success">

                                                ₹<?= number_format($row['total_amount'] ?? 0, 2) ?>

                                            </div>

                                            <small class="text-muted">

                                                <?= (int) $row['total_receipts'] ?>

                                                receipts

                                            </small>

                                        </div>

                                    </li>

                                <?php endwhile; ?>

                            </ul>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

<?php

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

?>