<?php
include('includes/dbconnection.php');

if (isset($_POST['discount_code']) && isset($_POST['feeType']) && isset($_POST['studentno'])) {
    $discountCode = $_POST['discount_code'];
    $feeType = $_POST['feeType'];
    $studentno = $_POST['studentno'];
    $originalAmount = $_POST['payAmount'] ?? 0;


    // Fetch the fee details
    $feeQuery = "SELECT * FROM fees WHERE name = '$feeType'";
    $feeResult = mysqli_query($con, $feeQuery);
    $fee = mysqli_fetch_assoc($feeResult);

    // Check the discount code from the database
    $discountCodeQuery = "SELECT * FROM discount_codes WHERE code = '$discountCode' AND expiry_date >= NOW()";
    $discountCodeResult = mysqli_query($con, $discountCodeQuery);

    if (mysqli_num_rows($discountCodeResult) > 0) {
        // Discount code is valid, fetch the discount percentage
        $discountRow = mysqli_fetch_assoc($discountCodeResult);
        $discountPercentage = $discountRow['discount_amount'];

        // Apply discount
        $discount = $discountPercentage;
        $newAmount = $originalAmount - ($originalAmount * ($discount / 100));
        $discountAmount = $originalAmount * ($discount / 100);

        echo json_encode([
            'success' => true,
            'newAmount' => $newAmount,
            'discountAmount' => $discountAmount,
        ]);
    } else {
        // Discount code is invalid or expired
        echo json_encode([
            'success' => false,
            'originalAmount' => $originalAmount,
            'message' => 'Invalid or expired discount code.'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request'
    ]);
}
