<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';
require_once __DIR__ . '/../../classes/Branch.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);
$loanLaybuy = new LoanLaybuy($conn);
$branch = new Branch($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: /IMS/login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['record_id'])) {
    try {
        $recordId = filter_input(INPUT_POST, 'record_id', FILTER_SANITIZE_NUMBER_INT);

        if (empty($recordId)) {
            throw new Exception("Invalid record ID provided.");
        }


        $recordData = $loanLaybuy->getLoanLaybuyById($recordId);
        if (!$recordData) {
            throw new Exception("Lay-buy record not found.");
        }


        $isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
        $userId = $_SESSION['user_id'];
        $userBranchId = $auth->getUserBranch($userId);
        $recordBranchId = $recordData['branch_id'] ?? null;
        $recordUserId = $recordData['user_id'] ?? null;

/*
        if (!$isSuperAdmin && ($userBranchId != $recordBranchId || $userId != $recordUserId)) {
            throw new Exception("You do not have permission to delete this loan or lay-buy record.");
        }
		*/


        $branchId = filter_input(INPUT_POST, 'branch_id', FILTER_SANITIZE_NUMBER_INT) ?? '';
        $searchTerm = filter_input(INPUT_POST, 'search_term', FILTER_SANITIZE_STRING) ?? '';
        $searchField = filter_input(INPUT_POST, 'search_field', FILTER_SANITIZE_STRING) ?? '';


        $conn->beginTransaction();
        $success = $loanLaybuy->deleteLoanLaybuy($recordId);

        if ($success) {
            $conn->commit();

            $queryParams = http_build_query([
                'success' => 'Lay-buy record deleted successfully.',
                'branch_id' => $branchId,
                'search_term' => $searchTerm,
                'search_field' => $searchField
            ]);
            header('Location: laybuy_and_loans.php?' . $queryParams);
        } else {
            $conn->rollBack();
            throw new Exception("Failed to delete the loan or lay-buy record.");
        }
    } catch (Exception $e) {
        if ($conn->inTransaction()) {
            $conn->rollBack();
        }
        error_log("Error processing loan/laybuy deletion for record_id=$recordId: " . $e->getMessage());
        header('Location: laybuy_and_loans.php?error=' . urlencode($e->getMessage()));
    }
    exit();
} else {
    $error = 'Invalid request method or missing record ID.';
    error_log($error . " Request method: {$_SERVER['REQUEST_METHOD']}, POST data: " . json_encode($_POST));
    header('Location: laybuy_and_loans.php?error=' . urlencode($error));
    exit();
}
?>