<?php
session_start();
// Include your database connection code
require_once 'shikanisha.kts.php';

// Check for the HTTP request method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Assuming you have already connected to the database.

    // Add code to retrieve $modalAccId, $paymethod, and $amount from your form data.
    $modalAccId = $_POST['modalAccId'];
    $paymethod = $_POST['paymethod'];
    $amount = $_POST['amount'];
    $total = 0;

    // Start a transaction
    mysqli_autocommit($conn, false); // Disable autocommit

    // Flag to track the success of the entire transaction
    $transactionSuccess = true;
    $errorMessage = ''; // Initialize an error message variable

    try {
        // Step 0: Get client_id based on modalAccId
        $getClientIdQuery = "SELECT `client_id` FROM `client_acc` WHERE `acc_id` = '$modalAccId'";
        $getClientIdResult = mysqli_query($conn, $getClientIdQuery);

        if (!$getClientIdResult) {
            throw new Exception("Error getting client ID: " . mysqli_error($conn));
        }

        $clientData = mysqli_fetch_assoc($getClientIdResult);
        $clientId = $clientData['client_id'];

        // Step 1: Get phone_number based on client_id
        $getPhoneNumberQuery = "SELECT `phone_number` FROM `customers` WHERE `customer_id` = '$clientId'";
        $getPhoneNumberResult = mysqli_query($conn, $getPhoneNumberQuery);

        if (!$getPhoneNumberResult) {
            throw new Exception("Error getting phone number: " . mysqli_error($conn));
        }

        $phoneData = mysqli_fetch_assoc($getPhoneNumberResult);
        $phone = $phoneData['phone_number'];

        // Step 2: Insert into transaction_receipts table
        $insertTransactionQuery = "INSERT INTO `transaction_receipts`(`amount_received`, `total`, `payment_method`, `phone_number`, `seller_date`, `seller_name`) VALUES ('$amount','$total','payment', '$phone', NOW(), '{$_SESSION['user']}')";
        if (!mysqli_query($conn, $insertTransactionQuery)) {
            throw new Exception("Error inserting transaction receipt: " . mysqli_error($conn));
        }

        // Get the last inserted transaction ID
        $transid = mysqli_insert_id($conn);

        // Step 3: Insert into payments table
        $insertPaymentQuery = "INSERT INTO `payments`(`payment_method`, `trans_id`, `amount`) VALUES ('$paymethod', '$transid', '$amount')";
        if (!mysqli_query($conn, $insertPaymentQuery)) {
            throw new Exception("Error inserting payment: " . mysqli_error($conn));
        }

        // Step 4: Update client_acc table
        $updateClientAccQuery = "UPDATE `client_acc` SET `amount_owed` = `amount_owed` - '$amount' WHERE `acc_id` = '$modalAccId'";
        if (!mysqli_query($conn, $updateClientAccQuery)) {
            throw new Exception("Error updating client account: " . mysqli_error($conn));
        }

        // Step 5: Insert into client_trans table
        $insertClientTransQuery = "INSERT INTO `client_trans`(`trans_id`, `amount`, `date`, `type`, `method`, `stid`, `client_id`) VALUES ('$transid', '$amount', NOW(), 'Payment', '$paymethod', '$transid', '$modalAccId')";
        if (!mysqli_query($conn, $insertClientTransQuery)) {
            throw new Exception("Error inserting client transaction: " . mysqli_error($conn));
        }

        // Commit the transaction if all queries were successful
        mysqli_commit($conn);
    } catch (Exception $e) {
        // Something went wrong, rollback the transaction
        mysqli_rollback($conn);
        $transactionSuccess = false;
        $errorMessage = $e->getMessage();
    } finally {
        // Re-enable autocommit and close the database connection
        mysqli_autocommit($conn, true); // Re-enable autocommit
        mysqli_close($conn);
    }

    // Prepare the response data
    $responseData = [
        'success' => $transactionSuccess,
        'message' => $transactionSuccess ? 'Payment successful!' : 'Payment failed!',
        'error' => $errorMessage
    ];

    // Send the JSON response back to the client
    header('Content-Type: application/json');
    echo json_encode($responseData);
} else {
    // Invalid request method
    header('HTTP/1.0 405 Method Not Allowed');
}
?>
