<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/item/functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// Validate required fields
if (
    // !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    // !isset($postdata['branch_id']) || !checkIfIssetAndNotEmpty($postdata['branch_id']) ||
    !isset($postdata['item_id']) || !checkIfIssetAndNotEmpty($postdata['item_id']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['principal'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

// $institution_id = $postdata['institution_id'];
// $branch_id = $postdata['branch_id'];
$item_id = $postdata['item_id'];

$date = date('Y-m-d');
$time = time();

if ($postdata['function_type'] == "approve_transfer_item") {
    try {
        $status = $postdata['status']; // Get status from frontend (1 = Approved, -1 = Rejected)

        // Validate status value
        if ($status != 1 && $status != -1) {
            errorreturn("Invalid status value.");
        }

        // Check if the transfer request exists
        $check_sql = "SELECT * FROM inventory_transactions 
                      WHERE id = ? 
                      AND transfer_accepted_by IS NULL";
        $stmt = $conn_rjllearning_specific->prepare($check_sql);
        $stmt->execute([$item_id]);
        $transfer_request = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$transfer_request) {
            errorreturn("Transfer request not found or already processed.");
        }

        // Approve/Reject transfer by updating the record
        $update_sql = "UPDATE inventory_transactions 
                       SET transfer_accepted_at = ?, transfer_accepted_by = ?, status = ?
                       WHERE institution_id = ? AND id = ?";
        
        $stmt = $conn_rjllearning_specific->prepare($update_sql);
        $stmt->execute([$date, $username, $status, $institution_id, $item_id]);

        $message = ($status == 1) ? "Transfer approved successfully." : "Transfer rejected successfully.";
        successreturn($message);
    } catch (PDOException $e) {
        errorreturn([ "message" => "Database error: " . $e->getMessage()]);
    }
}
