<?php
include_once 'shikanisha.kts.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['trans_id'])) {
    $transId = $conn->real_escape_string($_POST['trans_id']);

    // Get the amount_received and phone_number
    $selectAmountStmt = $conn->prepare("SELECT `amount_received`, `phone_number` FROM `transaction_receipts` WHERE `trans_id` = ?");
    $selectAmountStmt->bind_param("i", $transId);
    $selectAmountStmt->execute();
    $amountResult = $selectAmountStmt->get_result();

    if ($amountResult->num_rows > 0) {
        $amountData = $amountResult->fetch_assoc();
        $amountReceived = $amountData['amount_received'];
        $phoneNumber = $amountData['phone_number'];

        // Get customer_id using phone_number
        $selectCustomerStmt = $conn->prepare("SELECT `customer_id` FROM `customers` WHERE `phone_number` = ?");
        $selectCustomerStmt->bind_param("s", $phoneNumber);
        $selectCustomerStmt->execute();
        $customerResult = $selectCustomerStmt->get_result();

        if ($customerResult->num_rows > 0) {
            $customerData = $customerResult->fetch_assoc();
            $customerId = $customerData['customer_id'];

            // Update client_acc
            $updateClientAccStmt = $conn->prepare("UPDATE `client_acc` SET `amount_owed` = `amount_owed` - ? WHERE `client_id` = ?");
            $updateClientAccStmt->bind_param("di", $amountReceived, $customerId);

            // Begin transaction
            $conn->begin_transaction();

            // Update client_acc
            if ($updateClientAccStmt->execute()) {
                // Prepare SQL statements to delete records
                $stmt1 = $conn->prepare("DELETE FROM transaction_receipts WHERE trans_id = ?");
                $stmt2 = $conn->prepare("DELETE FROM payments WHERE trans_id = ?");
                $stmt3 = $conn->prepare("DELETE FROM sales WHERE trans_id = ?");
                $stmt4 = $conn->prepare("DELETE FROM `client_trans` WHERE  `stid` = ?");
                
                // Bind parameters
                $stmt1->bind_param("i", $transId);
                $stmt2->bind_param("i", $transId);
                $stmt3->bind_param("i", $transId);
                $stmt4->bind_param("i", $transId);
                
                // Execute delete statements
                $deleteSuccess = $stmt1->execute() && $stmt2->execute() && $stmt3->execute() && $stmt4->execute();
                
                // Close the statements
                $stmt1->close();
                $stmt2->close();
                $stmt3->close();
                $stmt4->close();
                
                if ($deleteSuccess) {
                    // If all deletes are successful, commit the transaction
                    $conn->commit();
                    echo json_encode(['success' => true]);
                } else {
                    // If any delete fails, rollback and send an error response
                    $conn->rollback();
                    echo json_encode(['error' => 'Failed to delete records.']);
                }
            } else {
                // If the update fails, rollback and send an error response
                $conn->rollback();
                echo json_encode(['error' => 'Failed to update client account.']);
            }
            $updateClientAccStmt->close();
        } else {
            // If no customer found, rollback and send an error response
            $conn->rollback();
            echo json_encode(['error' => 'Customer not found.']);
        }
        $selectCustomerStmt->close();
    } else {
        // If no amount data found, rollback and send an error response
        $conn->rollback();
        echo json_encode(['error' => 'Transaction data not found.']);
    }
    $selectAmountStmt->close();
} else {
    // If it's an invalid request, send an error response
    echo json_encode(['error' => 'Invalid request']);
}
?>
