<?php
// Database connection
include("include/connection.php");

// Create connection
$conn = new mysqli($host, $user, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['memberNo'])) { // Ensure consistency with what the frontend sends
    $memberID = $_POST['memberNo'];

    // Query to check if the member has an active loan
    $loanQuery = "SELECT LoanBalance FROM loan WHERE memberNo = ? AND LoanBalance > 0 LIMIT 1";
    $loanStmt = $conn->prepare($loanQuery);

    if ($loanStmt === false) {
        die("Prepare failed: " . $conn->error);
    }

    // Bind the memberID parameter to the loan query
    $loanStmt->bind_param("i", $memberID);
    $loanStmt->execute();
    $loanResult = $loanStmt->get_result();

    // Check if the member has an active loan
    if ($loanResult->num_rows > 0) {
        // Member has an active loan, return alert message
        echo json_encode([
            'status' => 'error',
            'message' => 'Member still has an active loan. Cannot register a new loan.'
        ]);
    } else {
        // If no active loan, fetch the member's name
        $memberQuery = "SELECT memberName FROM member WHERE memberNo = ?";
        $memberStmt = $conn->prepare($memberQuery);

        if ($memberStmt === false) {
            die("Prepare failed: " . $conn->error);
        }

        // Bind the memberID parameter to the member query
        $memberStmt->bind_param("i", $memberID);
        $memberStmt->execute();
        $memberResult = $memberStmt->get_result();

        // Check if member exists
        if ($memberResult->num_rows > 0) {
            $memberRow = $memberResult->fetch_assoc();
            // Return the member name as success response
            echo json_encode([
                'status' => 'success',
                'memberName' => $memberRow['memberName']
            ]);
        } else {
            // Member not found
            echo json_encode([
                'status' => 'error',
                'message' => 'Member not found.'
            ]);
        }

        $memberStmt->close();
    }

    $loanStmt->close();
}

// Close connection
$conn->close();
?>
