<?php
include('db_connection.php');

/* =========================
   GENERATE RECEIPT NUMBER
========================= */
function generateReceiptNo($conn) {
    $prefix = "GGS";
    $today = date("Y-m-d");

    // ✅ FIX: use DATE() instead of LIKE
    $query = "SELECT COUNT(*) as count FROM payments WHERE DATE(date) = ?";
    $stmt = $conn->prepare($query);

    if (!$stmt) {
        die("Prepare failed (receipt): " . $conn->error);
    }

    $stmt->bind_param("s", $today);
    $stmt->execute();

    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $count = $row['count'] + 1;
    $stmt->close();

    return $prefix . date("Ymd") . sprintf("%04d", $count);
}


/* =========================
   VALIDATE INPUT
========================= */
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $purpose = isset($_POST['purpose']) ? trim($_POST['purpose']) : '';

    if ($student_id <= 0 || $amount <= 0 || empty($purpose)) {
        die("Invalid input data.");
    }

    $receipt_no = generateReceiptNo($conn);
    $date = date('Y-m-d');


    /* =========================
       INSERT INTO PAYMENTS
    ========================= */
    $payment_query = "INSERT INTO payments (student_id, amount, purpose, date, receipt_no) 
                      VALUES (?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($payment_query);

    if (!$stmt) {
        die("Prepare failed (payments): " . $conn->error);
    }

    $stmt->bind_param("idsss", $student_id, $amount, $purpose, $date, $receipt_no);

    if (!$stmt->execute()) {
        die("Execute failed (payments): " . $stmt->error);
    }

    $payment_id = $stmt->insert_id;
    $stmt->close();


    /* =========================
       INSERT INTO RECEIPTS
    ========================= */
    $receipt_query = "INSERT INTO receipts (student_id, payment_id, receipt_no, date) 
                      VALUES (?, ?, ?, ?)";

    $stmt = $conn->prepare($receipt_query);

    if (!$stmt) {
        die("Prepare failed (receipts): " . $conn->error);
    }

    $stmt->bind_param("iiss", $student_id, $payment_id, $receipt_no, $date);

    if (!$stmt->execute()) {
        die("Execute failed (receipts): " . $stmt->error);
    }

    $stmt->close();


    /* =========================
       UPDATE STUDENT FEES
    ========================= */
    $update_fees_query = "UPDATE students 
                          SET fees_paid = fees_paid + ?, 
                              fees_outstanding = fees_outstanding - ? 
                          WHERE student_id = ?";

    $stmt = $conn->prepare($update_fees_query);

    if (!$stmt) {
        die("Prepare failed (update): " . $conn->error);
    }

    $stmt->bind_param("ddi", $amount, $amount, $student_id);

    if (!$stmt->execute()) {
        die("Execute failed (update): " . $stmt->error);
    }

    $stmt->close();


    /* =========================
       REDIRECT
    ========================= */
    header('Location: select_receipt_format.php?id=' . $payment_id);
    exit();

} else {
    echo "Invalid request.";
}
?>