<?php

session_start();

require_once __DIR__ . '/../../library/config.php';
require_once __DIR__ . '/../../library/super_admin_auth.php';
require_once __DIR__ . '/../../library/super_admin_audit_log.php';

// ======================================================
// VALIDATE ID
// ======================================================

$invoice_id = (int) ($_GET['id'] ?? 0);

if ($invoice_id <= 0) {

    header('Location: view_invoices.php');
    exit;
}

// ======================================================
// SUPER ADMIN DATA
// ======================================================

$super_admin_id = $_SESSION['super_admin_id'] ?? null;
$super_admin_name = $_SESSION['super_admin_name'] ?? 'Unknown';
$super_admin_email = $_SESSION['super_admin_email'] ?? 'Unknown';

try {

    // ==================================================
    // FETCH INVOICE
    // ==================================================

    $stmt = $pdo->prepare("
        SELECT *
        FROM invoices
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([$invoice_id]);

    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$invoice) {

        header('Location: view_invoices.php');
        exit;
    }

    // ==================================================
    // DELETE INVOICE
    // ==================================================

    $deleteStmt = $pdo->prepare("
        DELETE FROM invoices
        WHERE id = ?
        LIMIT 1
    ");

    $deleteStmt->execute([$invoice_id]);

    // ==================================================
    // AUDIT LOG
    // ==================================================

    try {

        logSuperAdminActivity($pdo, [

            'super_admin_id'     => $super_admin_id,
            'super_admin_email'  => $super_admin_email,
            'super_admin_name'   => $super_admin_name,

            'module'             => 'Invoice Management',

            'action'             => 'DELETE',

            'record_id'          => $invoice_id,

            'message'            => "Invoice deleted: {$invoice['invoice_no']}",

            'old_data'           => $invoice,

            'new_data'           => null
        ]);

    } catch (Exception $log_error) {

        error_log(
            'DELETE INVOICE AUDIT ERROR: ' .
            $log_error->getMessage()
        );
    }

}

catch (Exception $e) {

    error_log(
        'DELETE INVOICE ERROR: ' .
        $e->getMessage()
    );
}

header('Location: view_invoices.php');

exit;