<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require('config.php');

// Prepare response array
$response = ["error" => false, "message" => ""];

// Validate required POST parameters
if (isset($_POST['releaseAction'], $_POST['quantity'], $_POST['stockID'], $_POST['date'], $_POST['requestedBy'], $_POST['destination'], $_POST['transID'])) {
    $releaseAction = $_POST['releaseAction'];
    $quantity = (int)$_POST['quantity'];
    $stockID = (int)$_POST['stockID'];
    $date = $_POST['date'];
    $requestedBy = (int)$_POST['requestedBy'];
    $destination = $_POST['destination'];
    $transID = $_POST['transID'];

    // Check current status of stock_requests
    $checkStatusQuery = "SELECT status FROM stock_requests WHERE requestID = ?";
    $stmt = $connect->prepare($checkStatusQuery);
    $stmt->bind_param("i", $transID);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $response["error"] = true;
        $response["message"] = "Invalid stock request ID.";
        echo json_encode($response);
        exit;
    }

    $row = $result->fetch_assoc();
    $currentStatus = $row['status'];

    // Check if already confirmed or declined
    if ($currentStatus === "Confirmed" && $releaseAction === "Confirm") {
        $response["error"] = true;
        $response["message"] = "This stock request is already confirmed.";
        echo json_encode($response);
        exit;
    } elseif ($currentStatus === "Declined" && $releaseAction === "Decline") {
        $response["error"] = true;
        $response["message"] = "This stock request is already declined.";
        echo json_encode($response);
        exit;
    }

    if ($releaseAction === "Confirm") {
        // Start transaction
        $connect->begin_transaction();

        // Flag to track errors
        $transactionSuccessful = true;

        // Subtract quantity from store_stock
        $updateStoreStockQuery = "UPDATE store_stock SET quantity = quantity - ? WHERE id = ?";
        $stmt = $connect->prepare($updateStoreStockQuery);
        $stmt->bind_param("ii", $quantity, $stockID);
        if (!$stmt->execute() || $stmt->affected_rows === 0) {
            $response["error"] = true;
            $response["message"] = "Insufficient stock or invalid stockID.";
            $transactionSuccessful = false;
        }

        // Update stock_requests status to Confirmed
        if ($transactionSuccessful) {
            $updateStockRequestsQuery = "UPDATE stock_requests SET status = 'Confirmed' WHERE requestID = ?";
            $stmt = $connect->prepare($updateStockRequestsQuery);
            $stmt->bind_param("i", $transID);
            if (!$stmt->execute()) {
                $response["error"] = true;
                $response["message"] = "Failed to update stock_requests status.";
                $transactionSuccessful = false;
            }
        }

        // Insert into releaseRecords
        if ($transactionSuccessful) {
            $insertReleaseRecordQuery = "INSERT INTO releaseRecords (stockID, quantity, releaseType, _timestamp, releaseBy) VALUES (?, ?, ?, ?, ?)";
            $stmt = $connect->prepare($insertReleaseRecordQuery);
            $stmt->bind_param("iissi", $stockID, $quantity, $destination, $date, $requestedBy);
            if (!$stmt->execute()) {
                $response["error"] = true;
                $response["message"] = "Failed to insert into releaseRecords.";
                $transactionSuccessful = false;
            }
        }

        // Update stock quantity in the stock table
        if ($transactionSuccessful) {
            $updateStockQuery = "UPDATE stock SET quantity = quantity + ? WHERE productID = ?";
            $stmt = $connect->prepare($updateStockQuery);
            $stmt->bind_param("ii", $quantity, $stockID);
            if (!$stmt->execute()) {
                $response["error"] = true;
                $response["message"] = "Failed to update stock table.";
                $transactionSuccessful = false;
            }
        }

        // Commit or Rollback transaction
        if ($transactionSuccessful) {
            $connect->commit();
            $response["message"] = "Stock release confirmed and records updated successfully.";
        } else {
            $connect->rollback();
        }
    } elseif ($releaseAction === "Decline") {
        // Update stock_requests status to Declined
        $updateStockRequestsQuery = "UPDATE stock_requests SET status = 'Declined' WHERE requestID = ?";
        $stmt = $connect->prepare($updateStockRequestsQuery);
        $stmt->bind_param("i", $transID);
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            $response["message"] = "Stock release request declined successfully.";
        } else {
            $response["error"] = true;
            $response["message"] = "Failed to decline stock release request or invalid stockID.";
        }
    } else {
        $response["error"] = true;
        $response["message"] = "Invalid releaseAction value.";
    }
} else {
    $response["error"] = true;
    $response["message"] = "Missing required parameters.";
}

// Output response as JSON
echo json_encode($response);
?>
