<?php
require('config.php');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Initialize the response
$response = [];

// Check if the necessary POST data is present
if (isset($_POST['id'], $_POST['orderAction'])) {
    $id = intval($_POST['id']); // Ensure ID is an integer
    $orderAction = $_POST['orderAction']; // The action to perform
    $actionReason = isset($_POST['reason']) ? $_POST['reason'] : null; // Reason to record
    $postedAmount = isset($_POST['amount']) ? floatval($_POST['amount']) : null; // Ensure the amount is a float if provided

    try {
        if ($orderAction === "Rejected" || $orderAction === "Delete") {
    // Insert the action reason into the actionReason table
    $insertReasonStmt = $connect->prepare("INSERT INTO actionReason (transID, action, reason) VALUES (?, ?, ?)");
    if (!$insertReasonStmt) {
        throw new Exception("Failed to prepare statement for inserting action reason: " . $connect->error);
    }
    $insertReasonStmt->bind_param("iss", $id, $orderAction, $actionReason);
    if (!$insertReasonStmt->execute()) {
        throw new Exception("Failed to insert action reason: " . $insertReasonStmt->error);
    }

  if ($orderAction === "Delete" && isset($_POST['deleteData'])) {
    $deleteData = json_decode($_POST['deleteData'], true);

    if (!is_array($deleteData)) {
        throw new Exception("Invalid deleteData format.");
    }

    $connect->begin_transaction(); // Start transaction

    try {
        foreach ($deleteData as $item) {
            $transID = $item['transID'];
            $stockID = $item['stockID'];
            $quantity = $item['quantity'];

            // Update stock quantity
            $updateStockStmt = $connect->prepare("UPDATE stock SET quantity = quantity + ? WHERE productID = ?");
            if (!$updateStockStmt) {
                throw new Exception("Failed to prepare statement for updating stock: " . $connect->error);
            }
            $updateStockStmt->bind_param("ii", $quantity, $stockID);
            if (!$updateStockStmt->execute()) {
                throw new Exception("Failed to update stock quantity: " . $updateStockStmt->error);
            }
            $updateStockStmt->close();
        }

        // Delete transactions and related credit payments
        $transIDs = array_column($deleteData, 'transID');
        $transIDs = array_unique($transIDs); // Ensure unique transIDs

        $placeholders = implode(',', array_fill(0, count($transIDs), '?'));

        // Delete from creditsPayments
        $deleteCreditsStmt = $connect->prepare("DELETE FROM creditsPayments WHERE transID IN ($placeholders)");
        if (!$deleteCreditsStmt) {
            throw new Exception("Failed to prepare statement for deleting credit payments: " . $connect->error);
        }
        $deleteCreditsStmt->bind_param(str_repeat("i", count($transIDs)), ...$transIDs);
        if (!$deleteCreditsStmt->execute()) {
            throw new Exception("Failed to delete credit payments: " . $deleteCreditsStmt->error);
        }
        $deleteCreditsStmt->close();

        // Delete from transactions
        $deleteStmt = $connect->prepare("DELETE FROM transactions WHERE trans_id IN ($placeholders)");
        if (!$deleteStmt) {
            throw new Exception("Failed to prepare statement for deleting transactions: " . $connect->error);
        }
        $deleteStmt->bind_param(str_repeat("i", count($transIDs)), ...$transIDs);
        if (!$deleteStmt->execute()) {
            throw new Exception("Failed to delete transactions: " . $deleteStmt->error);
        }
        $deleteStmt->close();

        $connect->commit(); // Commit transaction
    } catch (Exception $e) {
        $connect->rollback(); // Rollback in case of error
        throw $e;
    }
}



    $response['error'] = false;
    $response['message'] = "Action '$orderAction' recorded with reason, and transaction deleted successfully.";
} elseif ($orderAction === "Mark_as_Paid") {
            if ($postedAmount === null) {
                $response['error'] = true;
                $response['message'] = "Amount must be provided for 'Mark_as_Paid' action.";
                echo json_encode($response);
                exit;
            }

            // Set the default timezone to East African Time
            date_default_timezone_set('Africa/Nairobi');

            // Start a transaction to ensure consistency
            $connect->begin_transaction();

            try {
                // Retrieve the current amount and status from the credits table
                $getCreditStmt = $connect->prepare("SELECT trans_amount FROM transactions WHERE trans_id = ?");
                if (!$getCreditStmt) {
                    throw new Exception("Failed to prepare statement for fetching credit amount: " . $connect->error);
                }
                $getCreditStmt->bind_param("i", $id);
                $getCreditStmt->execute();
                $getCreditStmt->bind_result($currentAmount);
                if (!$getCreditStmt->fetch()) {
                    throw new Exception("No associated credit record found for transaction ID $id.");
                }
                $getCreditStmt->close();

                // Calculate the new balance after payment
                $newBalance = $currentAmount + $postedAmount;

                // Update the status in the credits table based on the new balance
                $newStatus = ($newBalance >= 0) ? "Fully Paid" : "Partially Paid";
                 $updateCreditsStmt = $connect->prepare("UPDATE transactions SET trans_amount = ? WHERE trans_id = ?");
                if (!$updateCreditsStmt) {
                    throw new Exception("Failed to prepare statement for updating credits: " . $connect->error);
                }
                $updateCreditsStmt->bind_param("di", $newBalance, $id);
                if (!$updateCreditsStmt->execute()) {
                    throw new Exception("Failed to execute credits update: " . $updateCreditsStmt->error);
                }

                // Insert the payment transaction into the creditsPayments table
                $insertPaymentStmt = $connect->prepare("INSERT INTO creditsPayments (transID, amountPaid, initialBalance, newBalance, paymentDate, status) 
                    VALUES (?, ?, ?, ?, ?, ?)");
                if (!$insertPaymentStmt) {
                    throw new Exception("Failed to prepare statement for inserting payment into creditsPayments: " . $connect->error);
                }

                // Prepare the current datetime in EAT
                $currentDateTimeEAT = date("Y-m-d H:i:s");

                $insertPaymentStmt->bind_param("idddss", $id, $postedAmount, $currentAmount, $newBalance, $currentDateTimeEAT, $newStatus);
                if (!$insertPaymentStmt->execute()) {
                    throw new Exception("Failed to execute insert into creditsPayments: " . $insertPaymentStmt->error);
                }

                // Commit the transaction
                $connect->commit();
                $response['error'] = false;
                $response['message'] = "New balance is $newBalance. Credits updated to '$newStatus'. Payment recorded.";
            } catch (Exception $e) {
                // Rollback the transaction in case of error
                if ($connect->in_transaction()) {
                    $connect->rollback();
                }
                $response['error'] = true;
                $response['message'] = "Exception occurred: " . $e->getMessage();
            }
        } else {
            // Update the status in the transactions table for other actions
            
            $updateStmt->bind_param("si", $orderAction, $id);
            if ($updateStmt->execute()) {
                if ($updateStmt->affected_rows > 0) {
                    $response['error'] = false;
                    $response['message'] = "Transaction ID $id updated successfully.";
                } else {
                    $response['error'] = true;
                    $response['message'] = "Transaction ID $id not found or status is already $orderAction.";
                }
            } else {
                $response['error'] = true;
                $response['message'] = "Failed to update status: " . $updateStmt->error;
            }
        }
    } catch (Exception $e) {
        // Rollback in case of exception
        $connect->rollback();
        $response['error'] = true;
        $response['message'] = "Exception: " . $e->getMessage();
    }
} else {
    $response['error'] = true;
    $response['message'] = "Invalid parameters.";
}

echo json_encode($response);
?>
