<?php
session_start();

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

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

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

$auth = new Auth($conn);
$invoice = new Invoice($conn, $logger);
$branch = new Branch($conn);


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


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['invoice_id'])) {

    try {
        $invoiceId = filter_input(INPUT_POST, 'invoice_id', FILTER_SANITIZE_NUMBER_INT);

        if (empty($invoiceId)) {
            throw new Exception("Invalid invoice ID.");
        }

       
        $invoiceData = $invoice->getInvoiceById($invoiceId);

        if (!$invoiceData) {
            throw new Exception("Invoice not found.");
        }

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

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

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

        
        $success = $invoice->deleteInvoice($invoiceId);

        if ($success) {

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

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

        } else {
            throw new Exception("Failed to delete the invoice.");
        }

    } catch (Exception $e) {

        error_log("Error deleting invoice: " . $e->getMessage());

        header('Location: list_invoices.php?error=' . urlencode($e->getMessage()));
        exit();
    }

} else {

    header('Location: list_invoices.php?error=' . urlencode('Invalid request method.'));
    exit();
}
?>