<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/DeliveryNote.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Logger.php';

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: list_delivery_note.php?error=' . urlencode('Invalid request method.'));
    exit();
}

$deliveryNoteId = filter_input(INPUT_POST, 'delivery_note_id', FILTER_VALIDATE_INT);

if (!$deliveryNoteId || $deliveryNoteId <= 0) {
    header('Location: list_delivery_note.php?error=' . urlencode('Invalid delivery note ID.'));
    exit();
}

$branchId    = $_POST['branch_id'] ?? '';
$searchTerm  = $_POST['search_term'] ?? '';
$searchField = $_POST['search_field'] ?? '';

try {

    $logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
    $auth = new Auth($conn);
	$logger = new Logger($conn);
    $deliveryNote = new DeliveryNote($conn);

    $deliveryNoteData = $deliveryNote->getDeliveryNoteById($deliveryNoteId);

    if (!$deliveryNoteData || !is_array($deliveryNoteData)) {
        throw new Exception("Delivery note not found.");
    }

    $isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
    $userBranchId = $auth->getUserBranch($_SESSION['user_id']);
    $noteBranchId = $deliveryNoteData['branch_id'] ?? null;

    if (!$isSuperAdmin && $userBranchId != $noteBranchId) {
        throw new Exception("You do not have permission to delete this delivery note.");
    }

    $success = $deliveryNote->deleteDeliveryNote($deliveryNoteId);

    if (!$success) {
        throw new Exception("Failed to delete the delivery note.");
    }

    $queryParams = http_build_query([
        'success' => 'Delivery note deleted successfully.',
        'branch_id' => $branchId,
        'search_term' => $searchTerm,
        'search_field' => $searchField
    ]);

    header('Location: list_delivery_note.php?' . $queryParams);
    exit();

} catch (Exception $e) {

    error_log("Delete Delivery Note Error: " . $e->getMessage());

    $queryParams = http_build_query([
        'error' => $e->getMessage(),
        'branch_id' => $branchId,
        'search_term' => $searchTerm,
        'search_field' => $searchField
    ]);

    header('Location: list_delivery_note.php?' . $queryParams);
    exit();
}