<?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 = 'Edit Fees Receipt';

// ======================================================
// GET RECEIPT
// ======================================================

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

if ($receipt_id <= 0) {

    header('Location:view_fees.php?msg=Invalid receipt');

    exit;
}

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

$stmt = $pdo->prepare("
    SELECT

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

        s.name,

        ss.roll_no,
        ss.section,

        c.class_name,

        sp.father_name,
        sp.father_phone

    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

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

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

    LIMIT 1
");

$stmt->execute([

    $receipt_id,
    $school_id,
    $current_session_id

]);

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

// ======================================================
// VALIDATE RECEIPT
// ======================================================

if (!$receipt) {

    header(
        'Location:view_fees.php?msg=Receipt not found'
    );

    exit;
}

// ======================================================
// UPDATE RECEIPT
// ======================================================

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

    try {

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

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

        $payment_date = trim(
            $_POST['payment_date'] ?? ''
        );

        $allowed_modes = [

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

        ];

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

        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.'
            );
        }

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

        $old_data = [

            'paid_amount' =>
                $receipt['paid_amount'],

            'payment_mode' =>
                $receipt['payment_mode'],

            'payment_date' =>
                $receipt['payment_date']

        ];

        $pdo->beginTransaction();

        // ==============================================
        // UPDATE
        // ==============================================

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

            SET

                paid_amount = ?,
                payment_mode = ?,
                payment_date = ?

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

        $stmt->execute([

            $paid_amount,

            $payment_mode,

            $payment_date,

            $receipt_id,

            $school_id,

            $current_session_id

        ]);

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Fees',

            'action' => 'UPDATE',

            'record_id' => $receipt_id,

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

            'old_data' => $old_data,

            'new_data' => [

                'paid_amount' =>
                    $paid_amount,

                'payment_mode' =>
                    $payment_mode,

                'payment_date' =>
                    $payment_date

            ]

        ]);

        $pdo->commit();

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

        exit;

    } catch (Exception $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }

        $error = $e->getMessage();
    }
}

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-edit text-warning"></i>

                        Edit Fees Receipt

                    </h1>

                    <small class="text-muted">

                        Receipt :
                        <?= htmlspecialchars($receipt['receipt_no']) ?>

                    </small>

                </div>

                <div>

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

                        <i class="fas fa-arrow-left"></i>

                        Back

                    </a>

                </div>

            </div>

        </div>

    </section>

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

    <section class="content">

        <div class="container-fluid">

            <!-- ALERT -->

            <?php if (isset($error)) : ?>

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

                    <?= htmlspecialchars($error) ?>

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

                </div>

            <?php endif; ?>

            <div class="row">

                <!-- ====================================== -->
                <!-- RECEIPT PREVIEW -->
                <!-- ====================================== -->

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

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

                        <div class="card-header">

                            <h3 class="card-title">

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

                                Receipt Preview

                            </h3>

                        </div>

                        <div class="card-body">

                            <div class="row">

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

                                    <div class="mb-3">

                                        <small class="text-muted d-block">

                                            Receipt No

                                        </small>

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

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

                                        </h4>

                                    </div>

                                    <div class="mb-3">

                                        <small class="text-muted d-block">

                                            Student

                                        </small>

                                        <strong>

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

                                        </strong>

                                    </div>

                                    <div class="mb-3">

                                        <small class="text-muted d-block">

                                            Roll No

                                        </small>

                                        <strong>

                                            <?= htmlspecialchars($receipt['roll_no'] ?? '-') ?>

                                        </strong>

                                    </div>

                                    <div class="mb-3">

                                        <small class="text-muted d-block">

                                            Class

                                        </small>

                                        <strong>

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

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

                                        </strong>

                                    </div>

                                    <div class="mb-3">

                                        <small class="text-muted d-block">

                                            Father Name

                                        </small>

                                        <strong>

                                            <?= htmlspecialchars($receipt['father_name'] ?? '-') ?>

                                        </strong>

                                    </div>

                                    <div>

                                        <small class="text-muted d-block">

                                            Phone

                                        </small>

                                        <strong>

                                            <?= htmlspecialchars($receipt['father_phone'] ?? '-') ?>

                                        </strong>

                                    </div>

                                </div>

                                <div class="col-12 col-md-6 text-md-right">

                                    <small class="text-muted d-block mb-2">

                                        Amount Received

                                    </small>

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

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

                                    </h1>

                                    <div class="mt-3">

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

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

                                        </span>

                                    </div>

                                    <div class="mt-3 text-muted">

                                        <?= date(
                                            'd M Y h:i A',
                                            strtotime($receipt['created_at'])
                                        ) ?>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

                <!-- ====================================== -->
                <!-- QUICK ACTIONS -->
                <!-- ====================================== -->

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

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

                        <div class="card-header">

                            <h3 class="card-title">

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

                                Quick Actions

                            </h3>

                        </div>

                        <div class="card-body">

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

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

                                Print Receipt

                            </a>

                            <a
                                href="view_fees.php?delete=<?= $receipt_id ?>"
                                class="btn btn-danger btn-block"
                                onclick="return confirm('Delete this receipt?')"
                            >

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

                                Delete Receipt

                            </a>

                        </div>

                    </div>

                </div>

            </div>

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

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

                        Update Payment Details

                    </h3>

                </div>

                <form method="POST" id="updateForm">

                    <div class="card-body">

                        <div class="row">

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

                                <label>

                                    Amount (₹) *

                                </label>

                                <input
                                    type="number"
                                    name="paid_amount"
                                    class="form-control"
                                    min="1"
                                    step="0.01"
                                    required
                                    value="<?= htmlspecialchars($receipt['paid_amount']) ?>"
                                >

                            </div>

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

                                <label>

                                    Payment Mode *

                                </label>

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

                                    <option value="">

                                        Select Mode

                                    </option>

                                    <option
                                        value="Cash"
                                        <?= ($receipt['payment_mode'] === 'Cash') ? 'selected' : '' ?>
                                    >

                                        💵 Cash

                                    </option>

                                    <option
                                        value="UPI"
                                        <?= ($receipt['payment_mode'] === 'UPI') ? 'selected' : '' ?>
                                    >

                                        📱 UPI

                                    </option>

                                    <option
                                        value="Card"
                                        <?= ($receipt['payment_mode'] === 'Card') ? 'selected' : '' ?>
                                    >

                                        💳 Card

                                    </option>

                                    <option
                                        value="Cheque"
                                        <?= ($receipt['payment_mode'] === 'Cheque') ? 'selected' : '' ?>
                                    >

                                        🧾 Cheque

                                    </option>

                                </select>

                            </div>

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

                                <label>

                                    Payment Date *

                                </label>

                                <input
                                    type="date"
                                    name="payment_date"
                                    class="form-control"
                                    required
                                    value="<?= htmlspecialchars($receipt['payment_date']) ?>"
                                >

                            </div>

                        </div>

                    </div>

                    <div class="card-footer">

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

                            <a
                                href="view_fees.php"
                                class="btn btn-secondary mb-2 mb-md-0 mr-md-2"
                            >

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

                                Cancel

                            </a>

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

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

                                Update Receipt

                            </button>

                        </div>

                    </div>

                </form>

            </div>

        </div>

    </section>

</div>

<script>

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

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

<?php

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

?>