<?php
include("../database/auth_check.php");  

$con = mysqli_connect("localhost", "root", "", "WSAS");
if (!$con) {
    die("Database connection failed: " . mysqli_connect_error());
}

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

    $sp_id = intval($_POST['sp_id']);
    $action = $_POST['action'];
    $description = $_POST['description'] ?? '';
    $payment_type = $_POST['payment_type'] ?? '';
    $source = $_POST['source'] ?? 'admin';

    // To determine status
    $status = '';

    if ($action === 'verify') {
        $status = 'Verified';
    } elseif ($action === 'decline') {
        $status = 'Declined';
    } elseif ($action === 'underpaid') {
        $status = 'Underpaid';
    }

    // Auto-verify downpayment during enrollment
    $isAuto = ($payment_type === 'Downpayment' && $source === 'enrollment');

    if ($isAuto) {
        $status = 'Verified';
    }

    if ($status !== '') {

        // Check current status
        $check = $con->prepare("SELECT spay_image, spay_status FROM student_payment WHERE sp_id = ?");
        $check->bind_param("i", $sp_id);
        $check->execute();
        $res = $check->get_result();
        $current = $res->fetch_assoc();

        if (!$current) {
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }

        $lockedStatuses = ['Verified', 'Declined', 'Underpaid'];

        if (in_array($current['spay_status'], $lockedStatuses)) {
            // Prevent re-processing
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }

        // Move reciept file
        $oldImage = $current['spay_image'];
        $oldStatus = $current['spay_status'];

        $basePath = "../uploads/student_receipt/";

        $folders = [
            "Pending" => "pending_payment/",
            "Verified" => "verified_payment/",
            "Declined" => "declined_payment/",
            "Underpaid" => "underpaid_payment/"
        ];

        if (!empty($oldImage) && isset($folders[$oldStatus]) && isset($folders[$status])) {

            $oldPath = $basePath . $folders[$oldStatus] . $oldImage;
            $newPath = $basePath . $folders[$status] . $oldImage;

            if (file_exists($oldPath)) {
                rename($oldPath, $newPath);
            }
        }

        // Verified time
        if ($status === 'Verified') {
            $verified_at = date("Y-m-d H:i:s");
        } else {
            $verified_at = null;
        }

        // UD database
        $stmt = $con->prepare("
            UPDATE student_payment 
            SET spay_status = ?, 
                payment_type = ?, 
                description = ?, 
                verified_at = ?
            WHERE sp_id = ?
        ");

        $verified_at_param = $verified_at;

        $stmt->bind_param(
            "ssssi",
            $status,
            $payment_type,
            $description,
            $verified_at_param,
            $sp_id
        );

        $stmt->execute();
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$sy_query = mysqli_query($con, "SELECT * FROM school_year WHERE is_active = 1 LIMIT 1");
$active_sy = mysqli_fetch_assoc($sy_query);

$sy_id = $active_sy['sy_id'] ?? null;

$student_id = 1; 

$stmt = $con->prepare("
    SELECT *
    FROM enroll_student
    WHERE student_id = ?
    ORDER BY enroll_id DESC
    LIMIT 1
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$enroll = $stmt->get_result()->fetch_assoc();

$enroll_id = $enroll['enroll_id'] ?? null;

// Fees
$fee = [
    'down_payment' => 0,
    'monthly_fee' => 0,
    'balance_fee' => 0
];

if ($enroll_id) {
    $soaQuery = mysqli_query($con, "
        SELECT * FROM soa
        WHERE enroll_id = $enroll_id
        ORDER BY soa_date DESC
        LIMIT 1
    ");

    if ($soaQuery && mysqli_num_rows($soaQuery) > 0) {
        $fee = mysqli_fetch_assoc($soaQuery);
    }
}

$monthly_fee = floatval($fee['monthly_fee']);
$downpayment = floatval($fee['down_payment']);

// Get verified payments
$paymentQuery = mysqli_query($con, "
    SELECT spay_amount
    FROM student_payment
    WHERE student_id = $student_id
    AND spay_status = 'Verified'
    ORDER BY created_at ASC
");

$payments_result = mysqli_query($con, "
    SELECT sp.*, s.student_id_num, s.f_name, s.m_name, s.l_name
    FROM student_payment sp
    JOIN adminstudent s ON sp.student_id = s.student_id
    ORDER BY sp.created_at DESC
");

$payments = [];
$totalPaid = 0;

while ($row = mysqli_fetch_assoc($paymentQuery)) {
    $payments[] = floatval($row['spay_amount']);
    $totalPaid += floatval($row['spay_amount']);
}

//  Months
$months = ['Downpayment', 'Month 1', 'Month 2', 'Month 3', 'Month 4'];

$remaining = $totalPaid;

$plan = array_merge(
    [['label' => 'Downpayment', 'due' => $downpayment]],
    array_fill(0, 4, ['label' => 'Monthly Fee', 'due' => $monthly_fee])
);

$monthly_payments = [];

foreach ($plan as $index => $p) {

    $due = $p['due'];
    $paid = min($due, $remaining);
    $remaining -= $paid;

    $monthly_payments[] = [
        'month' => $months[$index],
        'amount_due' => $due,
        'amount_paid' => $paid,
        'balance' => $due - $paid,
        'status' => $paid >= $due ? 'Paid' : ($paid > 0 ? 'Partial' : 'Unpaid')
    ];
}

// Fetch students (for autofill)
$students = [];

$result = mysqli_query($con, "SELECT student_id_num, f_name, m_name, l_name FROM adminstudent");

while ($row = mysqli_fetch_assoc($result)) {
    $students[$row['student_id_num']] =
        $row['l_name'] . ", " . $row['f_name'] . " " . $row['m_name'];
}

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

    $student_id_num = $_POST['student_id_num'];
    $payment_type = $_POST['payment_type'];
    $subtype = $_POST['payment_subtype'] ?? null;
    $description = $_POST['description'] ?? '';
    $amount = floatval($_POST['amount']);
    $mode_of_payment = $_POST['mode_of_payment'];

    // get student_id from student_id_num
    $stmt = $con->prepare("SELECT student_id FROM adminstudent WHERE student_id_num = ?");
    $stmt->bind_param("s", $student_id_num);
    $stmt->execute();
    $res = $stmt->get_result();
    $student = $res->fetch_assoc();

    if (!$student) {
        die("Student not found.");
    }

    $student_id = $student['student_id'];

    // active school year
    $sy_query = mysqli_query($con, "SELECT sy_id FROM school_year WHERE is_active = 1 LIMIT 1");
    $sy = mysqli_fetch_assoc($sy_query);
    $sy_id = $sy['sy_id'] ?? null;

    // insert payment
    $insert = $con->prepare("
        INSERT INTO student_payment 
        (spay_amount, spay_image, spay_status, payment_type, description, sy_id, spay_method, student_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $spay_image = "-";
    $spay_status = "Verified"; // admin-added = auto verified

    $insert->bind_param(
        "dsssssii",
        $amount,
        $spay_image,
        $spay_status,
        $payment_type,
        $description,
        $sy_id,
        $mode_of_payment,
        $student_id
    );

    $insert->execute();

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Verify Payments - Admin </title>

<link rel="shortcut icon" type="x-icon" href="../images/logo.png">
<link rel="stylesheet" href="../Style/navstyle.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />

<style>
.dashboard-container {
    display: flex;
    height: 100vh;
    font-family: "Segoe UI", sans-serif;
    background-color: #f4f6f8;
}

.mainbar {
    margin-left: 260px;
    width: calc(100% - 260px);
    flex: 1;
    display: flex;
    flex-direction: column;
}

.mainbar-header {
    padding: 20px 25px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.mainbar-header h1 {
    font-size: 20px;
    color: #333;
    margin: 0;
    font-weight: 600;
}

.open-btn, .action-btn, .submit-btn {
    background-color: #4a9c3f;
    color: #fff;
    padding: 6px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    transition: background-color 0.3s;
}

.open-btn:hover, .verify-btn:hover, .submit-btn:hover {
    background-color: #3e8c36;
}

.submit-btn {
    display: block;
    margin: 30px auto 0 auto; 
}

.decline-btn {
    background-color: #EE7A02;
}

.decline-btn:hover {
    background-color: #c36100;
}

.mainbar-context {
    flex: 1;
    padding: 20px 25px;
    overflow-y: auto;
}

.container, .container1 {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    margin-bottom: 20px;
}

.payment-wrapper {
    max-height: 75vh;
    overflow: auto;
    border-radius: 10px;
    background-color: #4a9c3f;
    color: #fff;
    padding: 20px;
    flex: 1 1 300px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

table {
    width: 100%;
    border-collapse: collapse;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    text-align: center;
    background: #fff;
}

table th, table td {
    padding: 6px 6px;
    border-bottom: 1px solid #e0e0e0;
    font-size: 12px;
    color: #333;
}

table th {
    background-color: #4a9c3f;
    color: #fff;
    font-weight: 600;
}

table tr:nth-child(even) {
    background-color: #f9f9f9;
}

table tr:hover {
    background-color: rgba(74,156,63,0.1);
}

table thead th {
    position: sticky;
    top: 0;
    z-index: 10;
    background: #4a9c3f;
}

.no-transactions {
    padding-top: 10px;  
    text-align: center;  
    font-style: italic;  
    color: #303030;      
    font-size: 11px;  
}

.search-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.left, .right {
    display: flex;
    align-items: center;
}

.search-input {
    padding: 4px 10px;
    width: 200px;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 11px;
}

.search-input:focus {
    outline: none;
    border-color: #4a9c3f;
    box-shadow: 0 0 3px rgba(74,156,63,0.5);
}

.filter-select {
    padding: 4px 10px;
    width: 100px; 
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 11px;
}

.addmodal {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.addmodal .modal-content {
    background: #fff;
    max-width: 500px;   
    margin: auto;
    padding: 5px 10px; 
    overflow: hidden;
    display: flex;
    flex-direction: column;
    border-radius: 12px;
    font-size: 11px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.2);
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    inset: 0;
    background: rgba(0,0,0,0.5);
    padding: 10px;
    overflow-y: auto;

    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.modal-content {
    background: #fff;
    width: 900px;
    max-width: 95%;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0,0,0,0.25);
    position: relative; 
}

.modal-body {
    display: flex;
    gap: 0;
    padding: 15px;
    overflow-y: auto;
    flex: 1;
}

.modal-header {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center; 
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    position: relative; 
}

.modal-header .close-btn {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 22px;
    cursor: pointer;
}

.modal-header .close-btn:hover {
    color: #4a9c3f;   
}

.modal-grid {
    display: flex;
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

.modal-left {
    width: 50%;
    padding: 5px 20px 20px 20px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    overflow-y: auto;
    box-sizing: border-box;
    font-size: 11px;
    align-items: stretch; 
}

.modal-left h3 {
    text-align: center;
}

.modal-divider {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%;
    width: 1px;
    background: #e5e5e5;
    transform: translateX(-50%);
    pointer-events: none; 
    max-height: 100%;
}

.modal-left h3 {
    margin-bottom: 10px;
    font-size: 11px;
    font-weight: 600;
    text-align: center;
}

.modal-left p {
    font-size: 11px;
    text-align: left;
    
}

.modal-right {
    width: 50%;
    padding: 5px 20px 20px 20px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    overflow-y: auto;
    box-sizing: border-box;
    font-size: 11px;
    align-items: stretch; 
}

.modal-right h3 {
    margin-bottom: 10px;
    font-size: 11px;
    font-weight: 600;
    text-align: center;
}

.soa-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
    background: #fff;
}

.soa-table th,
.soa-table td {
    padding: 6px;
    text-align: center;
}

.soa-table tfoot td {
    font-size: 10px;
    font-size: 12px;
    padding: 2px 0;
}

.details-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 10px;
}

.student-details {
    flex: 1;
}

.date-details {
    text-align: right;
    flex-shrink: 0;
}

.date-details p {
    text-align: right;
}

.modal-image {
    width: 100%;
    max-height: 220px;
    object-fit: contain;
    border-radius: 8px;
    margin: 10px auto;
    display: block;
}

@keyframes pop {
    from { transform: scale(0.85); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
}

.description-input, 
.form-input {
    width: 100%;
    padding: 6px 12px;
    font-size: 11px;
    border-radius: 6px;
    border: 1px solid #ccc;
    outline: none;
    margin-top: 10px;
    transition: border-color 0.3s, box-shadow 0.3s;
}

.description-input:focus, 
.form-input:focus {
    border-color: #4a9c3f;
    box-shadow: 0 0 0 2px rgba(74,156,63,0.2);
}

.modal-buttons {
    margin-top: auto;
    display: flex;
    justify-content: center;
    gap: 15px;
    padding-top: 15px;
}

.modal-buttons button {
    font-size: 11px;
    font-weight: 600;
    padding: 6px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    background-color: #4a9c3f;
    color: #fff;
    transition: 0.3s;
}

.modal-buttons button:hover {
    background-color: #3e8c36;
}

.modal-buttons button:last-child {
    background-color: #EE7A02;
}

.modal-buttons button:last-child:hover {
    background-color: #c36100;
}

#subtype select,
#addSubtype select {
    font-size: 11px;
}

#subtype select,
#addSubtype select {
    font-size: 11px;
    padding: 3px 6px;
}
</style>
</head>

<body> 
   <div class="dashboard-container">
    <?php include('adminnav.php'); ?>

    <aside class="mainbar">

        <div class="mainbar-context">
            <div class="container1">
                <button id="openModal" class="open-btn"> ADD PAYMENT </button>
            </div>
            <div class="container">
                <div class="payment-wrapper">
                    <div class="search-container">
                        <select id="statusFilter" class="filter-select">
                            <option value="">All</option>
                            <option value="Verified">Verified</option>
                            <option value="Pending">Pending</option>
                            <option value="Declined">Declined</option>
                        </select>
                        <input type="text" id="transactionSearch" class="search-input" placeholder="Search Payments...">
                    </div>
                    <table id="payment-table">
                        <thead>
                        <tr>
                            <th> Student ID Number </th>
                            <th> Student Name </th>
                            <th> Date Sent </th>
                            <th> Date Verified </th>
                            <th> Payment Type </th>
                            <th> Amount </th>
                            <th> Receipt </th>
                            <th> Mode of Payment </th>
                            <th> Status </th>
                        </tr>
                        </thead>
                        <?php if ($payments_result && mysqli_num_rows($payments_result) > 0): ?>
                            <?php while($row = mysqli_fetch_assoc($payments_result)): ?>
                                <tr 
                                    data-sp_id="<?= $row['sp_id'] ?>"
                                    data-student="<?= htmlspecialchars($row['l_name'] . ", " . $row['f_name'] . " " . $row['m_name']) ?>"
                                    data-student_id="<?= $row['student_id_num'] ?>"
                                    data-amount="<?= number_format($row['spay_amount'], 2) ?>"
                                    data-date="<?= date("M d, Y", strtotime($row['created_at'])) ?>"
                                    data-time="<?= date("h:i A", strtotime($row['created_at'])) ?>"
                                    data-filename="<?= $row['spay_image'] ?>"
                                    data-status="<?= $row['spay_status'] ?>"
                                    >                       
                                    <td><?= $row['student_id_num'] ?></td>
                                    <td><?= htmlspecialchars($row['l_name'] . ", " . $row['f_name']) ?></td>
                                    <td><?= date("M d, Y", strtotime($row['created_at'])) ?> | <?= date("h:i A", strtotime($row['created_at'])) ?></td>
                                    <td>
                                        <?= !empty($row['verified_at']) 
                                            ? date("M d, Y | h:i A", strtotime($row['verified_at'])) 
                                            : '—' ?>
                                    </td>
                                    <td><?= htmlspecialchars($row['payment_type']) ?></td>
                                    <td><?= number_format($row['spay_amount'], 2) ?></td>
                                    <td>
                                    <?php if(!empty($row['spay_image']) && $row['spay_image'] !== '-'): ?>
                                        <span class="view-receipt">View</span>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars($row['spay_method']) ?></td>
                                    <td style="color: <?= $row['spay_status']=='Verified' ? 'green' : ($row['spay_status']=='Pending' ? 'orange' : 'red'); ?>">
                                        <?= $row['spay_status'] ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>                           
                        <?php else: ?>
                            <tr>
                                <td colspan="9" class="no-transactions"> No payments found. </td>
                            </tr>
                        <?php endif; ?> 
                    </table>
                </div>        
            </div>
        </div>
    </aside>

<!-- For payment modal -->
<div id="paymentModal" class="modal">
    <div class="modal-content">

        <div class="modal-header">
            <span id="closePaymentModal" class="close-btn">&times;</span>
        </div>

        <div class="modal-body">
            <div class="modal-grid">

                <!-- LEFT SIDE -->
                <div class="modal-left">
                    <h3>PAYMENT DETAILS</h3>

                    <div class="details-row">
                        <div class="student-details">
                            <p>Name: <span id="modalStudent"></span></p>
                            <p>Student ID Number: <span id="modalStudentID"></span></p>
                        </div>

                        <div class="date-details">
                            <p>Date: <span id="modalDate"></span></p>
                        </div>
                    </div>

                    <img id="modalReceipt" class="modal-image" alt="Receipt Image">

                    <p>Amount: ₱<span id="modalAmount"></span></p>

                    <div class="form-group">
                        <select id="paymentType" name="payment_type" class="form-input" required>
                            <option value="">Select Payment Type</option>
                            <option value="Tuition">Tuition</option>
                            <option value="Merchandise">Merchandise</option>
                        </select>

                        <div id="subtype" style="display:none;">
                            <select id="payment_subtype" name="payment_subtype">
                                <option value="">Select Subtype</option>
                                <option value="Downpayment">Downpayment</option>
                                <option value="Monthly Fee">Monthly Fee</option>
                            </select>
                        </div>
                    </div>

                    <input type="text" id="modalDescription" class="description-input" placeholder="Add description">

                    <div class="modal-buttons">
                        <button id="verifyBtn" disabled onclick="submitAction('verify')">Verify</button>
                        <button id="declineBtn" disabled onclick="submitAction('decline')">Decline</button>
                    </div>
                </div>

                <!-- DIVIDER -->
                <div class="modal-divider"></div>

                <!-- RIGHT SIDE -->
                <div class="modal-right">
                    <h3>STATEMENT OF ACCOUNT</h3>

                    <table class="soa-table">
                        <thead>
                            <tr>
                                <th>Monthly</th>
                                <th>Amount Due</th>
                                <th>Amount Paid</th>
                                <th>Status</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach ($monthly_payments as $pay): ?>
                            <tr>
                                <td><?= $pay['due'] ?></td>
                                <td>₱ <?= number_format($pay['amount_due'], 2) ?></td>
                                <td>₱ <?= number_format($pay['amount_paid'], 2) ?></td>
                                <td style="color:
                                    <?= $pay['status']=='Paid' ? 'green' :
                                        ($pay['status']=='Unpaid' ? 'red' : '#999'); ?>">
                                    <?= $pay['status'] ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>

                        <tfoot>
                            <tr style="font-weight:bold;">
                                <td colspan="2" style="text-align:center;">
                                    REMAINING BALANCE:
                                </td>
                                <td style="text-align:center;">
                                    ₱ <?= number_format($fee['balance_fee'] ?? 0, 2); ?>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Payment Modal -->
<div id="addPaymentModal" class="addmodal">
    <div class="modal-content">
        <div class="modal-header">
            <h3> ADD PAYMENT </h3>
            <span id="closeAddPaymentModal" class="close-btn">&times;</span>
        </div>

        <form id="addPaymentForm" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="source" value="admin">
            <input type="text" name="student_id_num" class="form-input" placeholder="Student ID Number" required>

            <input type="text" name="student_name" id="studentName" class="form-input" placeholder="Student Name" readonly>

            <select id="addpaymenttype" name="payment_type" class="form-input" required>
                <option value="">Select Payment Type</option>
                <option value="Tuition">Tuition</option>
                <option value="Merchandise">Merchandise</option>
            </select>
            <div id="addSubtype" style="display:none;">
                <select id="add_payment_subtype" name="payment_subtype">
                    <option value="">Select Subtype</option>
                    <option value="Downpayment">Downpayment</option>
                    <option value="Monthly Fee">Monthly Fee</option>
                </select>
            </div>
            <input type="text" name="description" class="form-input" placeholder="Description">
            <input type="text" name="amount" class="form-input" placeholder="Amount" required>
            <select name="mode_of_payment" class="form-input" required>
                <option value="">Select Mode of Payment</option>
                <option value="Online">Online</option>
                <option value="Cash">Cash</option>
            </select>
            <button type="submit" name="add_payment" class="submit-btn">Add Payment</button>
        </form>
    </div>
</div>

<script>
const table = document.getElementById('payment-table');

const paymentModal = document.getElementById('paymentModal');
const addPaymentModal = document.getElementById('addPaymentModal');

const openModalBtn = document.getElementById('openModal');

const closePaymentModal = document.getElementById('closePaymentModal');
const closeAddPaymentModal = document.getElementById('closeAddPaymentModal');

let currentSpId = null;

// Add payment modal (open/close)
openModalBtn.addEventListener('click', () => {
    addPaymentModal.style.display = 'flex';
});

closeAddPaymentModal.addEventListener('click', () => {
    addPaymentModal.style.display = 'none';
});

window.addEventListener('click', (e) => {
    if (e.target === addPaymentModal) addPaymentModal.style.display = 'none';
    if (e.target === paymentModal) paymentModal.style.display = 'none';
});

// Payment moda
const descriptionInput = document.getElementById('modalDescription');
const paymentTypeSelect = document.getElementById('paymentType');
const verifyBtn = document.getElementById('verifyBtn');
const declineBtn = document.getElementById('declineBtn');

const subtypeGroup = document.getElementById('subtype');
const paymentSubtype = document.getElementById('payment_subtype');

// For button control
function setButtonsDisabled(state) {
    verifyBtn.disabled = state;
    declineBtn.disabled = state;

    verifyBtn.style.opacity = state ? "0.5" : "1";
    declineBtn.style.opacity = state ? "0.5" : "1";

    verifyBtn.style.cursor = state ? "not-allowed" : "pointer";
    declineBtn.style.cursor = state ? "not-allowed" : "pointer";
}

// Validation
function validateModalFields() {
    const isValid =
        descriptionInput.value.trim().length > 0 &&
        paymentTypeSelect.value !== "";

    setButtonsDisabled(!isValid);
}

// Reset modal
function resetModal() {
    descriptionInput.value = "";
    paymentTypeSelect.value = "";
    paymentSubtype.value = "";
    subtypeGroup.style.display = "none";
    setButtonsDisabled(true);
}

// Payment type
paymentTypeSelect.addEventListener('change', function () {
    if (this.value === "Tuition") {
        subtypeGroup.style.display = "block";
    } else {
        subtypeGroup.style.display = "none";
        paymentSubtype.value = "";
    }

    validateModalFields();
});

descriptionInput.addEventListener('input', validateModalFields);

// Open modal when specific row is been clicked
table.querySelectorAll('tr[data-sp_id]').forEach(row => {
table.addEventListener('click', function (e) {
    const row = e.target.closest('tr[data-sp_id]');
    if (!row) return;

        currentSpId = row.dataset.sp_id;
        const status = this.dataset.status;

        document.getElementById('modalStudent').innerText = this.dataset.student;
        document.getElementById('modalStudentID').innerText = this.dataset.student_id;
        document.getElementById('modalDate').innerText = this.dataset.date + " | " + this.dataset.time;
        document.getElementById('modalAmount').innerText = this.dataset.amount;

        const receiptImg = document.getElementById('modalReceipt');
        const filename = this.dataset.filename;

        let folder = "";
        if (status === "Pending") folder = "pending_payment/";
        else if (status === "Verified") folder = "verified_payment/";
        else if (status === "Declined") folder = "declined_payment/";

        if (filename && filename !== '-') {
            receiptImg.src = `/WSAS/uploads/student_receipt/${folder}${filename}?t=${Date.now()}`;
            receiptImg.style.display = 'block';
        } else {
            receiptImg.style.display = 'none';
        }

        resetModal();

        const locked = ["Verified", "Declined", "Underpaid"].includes(status);

        descriptionInput.disabled = locked;
        paymentTypeSelect.disabled = locked;
        paymentSubtype.disabled = locked;

        if (locked) {
            setButtonsDisabled(true);
        } else {
            validateModalFields();
        }

        paymentModal.style.display = 'flex';
    });
});

// Verify/Decline
function submitAction(action) {
    const description = descriptionInput.value.trim();
    const paymentType = paymentTypeSelect.value.trim();

    if (!currentSpId) return;

    if (!description || !paymentType) {
        alert("Please complete all fields.");
        return;
    }

    if (!confirm(
        action === 'verify'
            ? "Are you sure you want to VERIFY this payment?"
            : "Are you sure you want to DECLINE this payment?"
    )) return;

    const form = document.createElement('form');
    form.method = 'POST';
    form.style.display = 'none';

    form.innerHTML = `
        <input name="sp_id" value="${currentSpId}">
        <input name="action" value="${action}">
        <input name="description" value="${description}">
        <input name="payment_type" value="${paymentType}">
    `;

    document.body.appendChild(form);
    form.submit();
}

// Close buttons
closePaymentModal.addEventListener('click', () => {
    paymentModal.style.display = 'none';
});

closeAddPaymentModal.addEventListener('click', () => {
    addPaymentModal.style.display = 'none';
});

// Search & Filter
const searchInput = document.getElementById('transactionSearch');
const statusFilter = document.getElementById('statusFilter');

function filterTable() {
    const search = searchInput.value.toLowerCase();
    const status = statusFilter.value;

    table.querySelectorAll('tr[data-sp_id]').forEach(row => {
        const text = row.innerText.toLowerCase();
        const rowStatus = row.dataset.status;

        const matchSearch = text.includes(search);
        const matchStatus = !status || rowStatus === status;

        row.style.display = (matchSearch && matchStatus) ? '' : 'none';
    });
}

searchInput.addEventListener('input', filterTable);
statusFilter.addEventListener('change', filterTable);

// Add payment validation
const addPaymentForm = document.getElementById('addPaymentForm');
const addPaymentType = document.getElementById('addpaymenttype');
const addSubtypeGroup = document.getElementById('addSubtype');
const addPaymentSubtype = document.getElementById('add_payment_subtype');

addPaymentType.addEventListener('change', function () {
    if (this.value === "Tuition") {
        addSubtypeGroup.style.display = "block";
    } else {
        addSubtypeGroup.style.display = "none";
        addPaymentSubtype.value = "";
    }
});

addPaymentForm.addEventListener('submit', function (e) {
    const formData = new FormData(addPaymentForm);

    const studentId = formData.get('student_id_num');
    const amount = formData.get('amount');
    const paymentTypeValue = formData.get('payment_type');
    const modeOfPayment = formData.get('mode_of_payment');

    if (!studentId || !amount || !paymentTypeValue || !modeOfPayment) {
        e.preventDefault();
        alert("Please complete all required fields.");
        return;
    }

    if (paymentTypeValue === "Tuition" && !addPaymentSubtype.value) {
        e.preventDefault();
        alert("Please select a subtype (Downpayment or Monthly Fee).");
        return;
    }

    if (!confirm("Are you sure you want to add this payment?")) {
        e.preventDefault();
    }
});

// For auto student name fill
const students = <?= json_encode($students) ?>;

const studentIdInput = document.querySelector('input[name="student_id_num"]');
const studentNameInput = document.getElementById('studentName');

studentIdInput.addEventListener('input', function () {
    const id = this.value.trim();

    if (!id) {
        studentNameInput.value = "";
        return;
    }

    studentNameInput.value = students[id] || "";
});
</script>

    <!-- Script -->
     <script src="../Jscript/script.js"></script>
</body>
</html>