<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'POS Approvals';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('pa_flash')) {
    function pa_flash(string $type, string $message): void {
        $_SESSION['pos_approvals_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('pa_get_flash')) {
    function pa_get_flash(): array {
        $items = $_SESSION['pos_approvals_flash'] ?? [];
        unset($_SESSION['pos_approvals_flash']);
        return $items;
    }
}
if (!function_exists('pa_table_exists')) {
    function pa_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
        ");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pa_column_exists')) {
    function pa_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("
            SELECT COUNT(*)
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = :table_name
              AND column_name = :column_name
        ");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('pa_add_col')) {
    function pa_add_col(PDO $pdo, string $table, string $column, string $sql): void {
        if (!pa_column_exists($pdo, $table, $column)) {
            $pdo->exec($sql);
        }
    }
}
if (!function_exists('pa_user_name_expr')) {
    function pa_user_name_expr(PDO $pdo, string $alias = 'u'): string {
        if (!pa_table_exists($pdo, 'users')) return "NULL";
        if (pa_column_exists($pdo, 'users', 'name')) return "{$alias}.name";
        if (pa_column_exists($pdo, 'users', 'full_name')) return "{$alias}.full_name";
        if (pa_column_exists($pdo, 'users', 'username')) return "{$alias}.username";
        if (pa_column_exists($pdo, 'users', 'email')) return "{$alias}.email";
        return "CONCAT('User #', {$alias}.id)";
    }
}
if (!function_exists('pa_current_role')) {
    function pa_current_role(): string {
        if (function_exists('current_user_role')) return (string)current_user_role();
        return (string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? $_SESSION['type'] ?? '');
    }
}
if (!function_exists('pa_current_user_id')) {
    function pa_current_user_id(): int {
        return (int)($_SESSION['user_id'] ?? $_SESSION['id'] ?? 0);
    }
}
if (!function_exists('pa_is_manager')) {
    function pa_is_manager(): bool {
        $role = strtolower(pa_current_role());
        return in_array($role, ['super_admin','admin','manager','owner','accounts'], true);
    }
}
if (!function_exists('pa_verify_manager_password')) {
    function pa_verify_manager_password(PDO $pdo, string $password): bool {
        if ($password === '') return false;

        /*
         * If no users table or password hash is unavailable, manager session role is enough.
         * This keeps the file usable in older installs.
         */
        if (!pa_table_exists($pdo, 'users')) {
            return pa_is_manager();
        }

        $userId = pa_current_user_id();
        if ($userId <= 0) return false;

        $passwordCol = null;
        foreach (['password_hash','password','user_password'] as $col) {
            if (pa_column_exists($pdo, 'users', $col)) {
                $passwordCol = $col;
                break;
            }
        }

        if (!$passwordCol) return pa_is_manager();

        $stmt = $pdo->prepare("SELECT {$passwordCol} FROM users WHERE id=:id LIMIT 1");
        $stmt->execute([':id' => $userId]);
        $hash = (string)($stmt->fetchColumn() ?: '');

        if ($hash === '') return false;

        if (password_verify($password, $hash)) return true;

        /*
         * Fallback for older systems using plain MD5/plain text.
         */
        if (hash_equals($hash, md5($password))) return true;
        if (hash_equals($hash, $password)) return true;

        return false;
    }
}
if (!function_exists('pa_request_no')) {
    function pa_request_no(PDO $pdo): string {
        $prefix = 'APP-' . date('ymd') . '-';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM pos_approval_requests WHERE request_no LIKE :p");
        $stmt->execute([':p' => $prefix . '%']);
        return $prefix . str_pad((string)((int)$stmt->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}
if (!function_exists('pa_insert_request')) {
    function pa_insert_request(PDO $pdo, array $data): int {
        $stmt = $pdo->prepare("
            INSERT INTO pos_approval_requests
            (request_no, approval_type, reference_type, reference_id, store_id, requested_by, amount, reason, status, metadata_json)
            VALUES
            (:request_no, :approval_type, :reference_type, :reference_id, :store_id, :requested_by, :amount, :reason, 'pending', :metadata_json)
        ");
        $stmt->execute([
            ':request_no' => pa_request_no($pdo),
            ':approval_type' => $data['approval_type'],
            ':reference_type' => $data['reference_type'] ?? null,
            ':reference_id' => $data['reference_id'] ?? null,
            ':store_id' => $data['store_id'] ?? null,
            ':requested_by' => pa_current_user_id() ?: null,
            ':amount' => $data['amount'] ?? 0,
            ':reason' => $data['reason'] ?? null,
            ':metadata_json' => !empty($data['metadata']) ? json_encode($data['metadata']) : null,
        ]);
        return (int)$pdo->lastInsertId();
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS store_locations (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        location_code VARCHAR(50) NULL,
        location_name VARCHAR(150) NOT NULL,
        location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
        is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        pos_no VARCHAR(60) NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        order_id INT UNSIGNED NULL,
        folio_id INT UNSIGNED NULL,
        guest_name VARCHAR(180) NULL,
        room_label VARCHAR(80) NULL,
        sale_type ENUM('cash','card','transfer','room_charge','complimentary','void') NOT NULL DEFAULT 'cash',
        payment_method VARCHAR(40) NULL,
        subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        tax_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        discount_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        status ENUM('open','paid','charged_to_room','void') NOT NULL DEFAULT 'open',
        notes TEXT NULL,
        void_reason TEXT NULL,
        voided_at DATETIME NULL,
        voided_by INT UNSIGNED NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_pos_no (pos_no),
        INDEX idx_pos_store (store_id),
        INDEX idx_pos_status (status),
        INDEX idx_pos_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_shifts (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        shift_no VARCHAR(60) NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        cashier_id INT UNSIGNED NULL,
        opened_by INT UNSIGNED NULL,
        closed_by INT UNSIGNED NULL,
        opened_at DATETIME NOT NULL,
        closed_at DATETIME NULL,
        opening_float DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        cash_drops DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        petty_cash_out DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        expected_cash DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        counted_cash DECIMAL(14,2) NULL,
        variance DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        cash_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        card_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        transfer_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        room_charge_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        complimentary_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        void_sales DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        receipt_count INT UNSIGNED NOT NULL DEFAULT 0,
        status ENUM('open','closed') NOT NULL DEFAULT 'open',
        opening_notes TEXT NULL,
        closing_notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_pos_shift_no (shift_no)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_approval_requests (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        request_no VARCHAR(60) NOT NULL,
        approval_type ENUM('void_receipt','discount','cash_variance','stock_adjustment','price_override','refund','other') NOT NULL DEFAULT 'other',
        reference_type VARCHAR(80) NULL,
        reference_id BIGINT UNSIGNED NULL,
        store_id INT UNSIGNED NULL,
        requested_by INT UNSIGNED NULL,
        approved_by INT UNSIGNED NULL,
        rejected_by INT UNSIGNED NULL,
        amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        reason TEXT NULL,
        manager_comment TEXT NULL,
        status ENUM('pending','approved','rejected','cancelled') NOT NULL DEFAULT 'pending',
        metadata_json JSON NULL,
        approved_at DATETIME NULL,
        rejected_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_pos_approval_no (request_no),
        INDEX idx_approval_status (status),
        INDEX idx_approval_type (approval_type),
        INDEX idx_approval_reference (reference_type, reference_id),
        INDEX idx_approval_store (store_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS pos_approval_audit (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        approval_id BIGINT UNSIGNED NULL,
        event_type ENUM('requested','approved','rejected','cancelled','auto_created','note') NOT NULL,
        event_note TEXT NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_approval_audit_approval (approval_id),
        INDEX idx_approval_audit_event (event_type)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    foreach ([
        'manager_comment' => "ALTER TABLE pos_approval_requests ADD COLUMN manager_comment TEXT NULL AFTER reason",
        'metadata_json' => "ALTER TABLE pos_approval_requests ADD COLUMN metadata_json JSON NULL AFTER status",
    ] as $col => $sql) {
        pa_add_col($pdo, 'pos_approval_requests', $col, $sql);
    }
} catch (Throwable $e) {
    $errors[] = 'Could not prepare approval tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'create_request') {
            $approvalType = (string)($_POST['approval_type'] ?? 'other');
            $referenceType = trim((string)($_POST['reference_type'] ?? 'manual'));
            $referenceId = (int)($_POST['reference_id'] ?? 0);
            $storeId = (int)($_POST['store_id'] ?? 0);
            $amount = (float)($_POST['amount'] ?? 0);
            $reason = trim((string)($_POST['reason'] ?? ''));

            $allowed = ['void_receipt','discount','cash_variance','stock_adjustment','price_override','refund','other'];
            if (!in_array($approvalType, $allowed, true)) $approvalType = 'other';
            if ($reason === '') throw new RuntimeException('Reason is required.');

            $approvalId = pa_insert_request($pdo, [
                'approval_type' => $approvalType,
                'reference_type' => $referenceType ?: 'manual',
                'reference_id' => $referenceId > 0 ? $referenceId : null,
                'store_id' => $storeId > 0 ? $storeId : null,
                'amount' => $amount,
                'reason' => $reason,
                'metadata' => [
                    'source' => 'manual',
                    'created_from' => 'pos_approvals.php',
                ],
            ]);

            $stmt = $pdo->prepare("
                INSERT INTO pos_approval_audit
                (approval_id, event_type, event_note, created_by)
                VALUES
                (:approval_id, 'requested', :event_note, :created_by)
            ");
            $stmt->execute([
                ':approval_id' => $approvalId,
                ':event_note' => $reason,
                ':created_by' => pa_current_user_id() ?: null,
            ]);

            pa_flash('success', 'Approval request created successfully.');
            header('Location: pos_approvals.php?view_id=' . $approvalId);
            exit;
        }

        if ($action === 'approve_request' || $action === 'reject_request' || $action === 'cancel_request') {
            $approvalId = (int)($_POST['approval_id'] ?? 0);
            $managerPassword = (string)($_POST['manager_password'] ?? '');
            $comment = trim((string)($_POST['manager_comment'] ?? ''));

            if ($approvalId <= 0) throw new RuntimeException('Invalid approval request.');

            $stmt = $pdo->prepare("SELECT * FROM pos_approval_requests WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $approvalId]);
            $request = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$request) throw new RuntimeException('Approval request not found.');

            if ($request['status'] !== 'pending') {
                throw new RuntimeException('This approval request is no longer pending.');
            }

            if ($action !== 'cancel_request') {
                if (!pa_is_manager()) throw new RuntimeException('Only a manager/admin can approve or reject.');
                if (!pa_verify_manager_password($pdo, $managerPassword)) {
                    throw new RuntimeException('Manager password/PIN is incorrect.');
                }
            }

            if ($action === 'approve_request') {
                $stmt = $pdo->prepare("
                    UPDATE pos_approval_requests
                    SET status='approved',
                        approved_by=:approved_by,
                        approved_at=NOW(),
                        manager_comment=:manager_comment
                    WHERE id=:id
                ");
                $stmt->execute([
                    ':approved_by' => pa_current_user_id() ?: null,
                    ':manager_comment' => $comment ?: null,
                    ':id' => $approvalId,
                ]);

                $eventType = 'approved';
                $msg = 'Approval request approved.';
            } elseif ($action === 'reject_request') {
                if ($comment === '') throw new RuntimeException('Please enter rejection comment.');

                $stmt = $pdo->prepare("
                    UPDATE pos_approval_requests
                    SET status='rejected',
                        rejected_by=:rejected_by,
                        rejected_at=NOW(),
                        manager_comment=:manager_comment
                    WHERE id=:id
                ");
                $stmt->execute([
                    ':rejected_by' => pa_current_user_id() ?: null,
                    ':manager_comment' => $comment,
                    ':id' => $approvalId,
                ]);

                $eventType = 'rejected';
                $msg = 'Approval request rejected.';
            } else {
                $stmt = $pdo->prepare("
                    UPDATE pos_approval_requests
                    SET status='cancelled',
                        manager_comment=:manager_comment
                    WHERE id=:id
                ");
                $stmt->execute([
                    ':manager_comment' => $comment ?: 'Cancelled by requester/user',
                    ':id' => $approvalId,
                ]);

                $eventType = 'cancelled';
                $msg = 'Approval request cancelled.';
            }

            $stmt = $pdo->prepare("
                INSERT INTO pos_approval_audit
                (approval_id, event_type, event_note, created_by)
                VALUES
                (:approval_id, :event_type, :event_note, :created_by)
            ");
            $stmt->execute([
                ':approval_id' => $approvalId,
                ':event_type' => $eventType,
                ':event_note' => $comment ?: $msg,
                ':created_by' => pa_current_user_id() ?: null,
            ]);

            pa_flash($eventType === 'approved' ? 'success' : 'warning', $msg);
            header('Location: pos_approvals.php?view_id=' . $approvalId);
            exit;
        }

        if ($action === 'auto_create_variance_requests') {
            $threshold = (float)($_POST['threshold'] ?? 5);
            if ($threshold < 0) $threshold = 0;

            $stmt = $pdo->prepare("
                SELECT ps.*
                FROM pos_shifts ps
                LEFT JOIN pos_approval_requests ar
                  ON ar.reference_type='pos_shift'
                 AND ar.reference_id=ps.id
                 AND ar.approval_type='cash_variance'
                 AND ar.status IN ('pending','approved')
                WHERE ps.status='closed'
                  AND ABS(ps.variance) >= :threshold
                  AND ar.id IS NULL
                ORDER BY ps.closed_at DESC
                LIMIT 100
            ");
            $stmt->execute([':threshold' => $threshold]);
            $shifts = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $created = 0;
            foreach ($shifts as $shift) {
                $approvalId = pa_insert_request($pdo, [
                    'approval_type' => 'cash_variance',
                    'reference_type' => 'pos_shift',
                    'reference_id' => (int)$shift['id'],
                    'store_id' => (int)$shift['store_id'],
                    'amount' => (float)$shift['variance'],
                    'reason' => 'Cash variance requires manager approval. Shift: ' . $shift['shift_no'] . ', Variance: ' . money_fmt($shift['variance']),
                    'metadata' => [
                        'shift_no' => $shift['shift_no'],
                        'expected_cash' => $shift['expected_cash'],
                        'counted_cash' => $shift['counted_cash'],
                        'variance' => $shift['variance'],
                    ],
                ]);

                $stmtAudit = $pdo->prepare("
                    INSERT INTO pos_approval_audit
                    (approval_id, event_type, event_note, created_by)
                    VALUES
                    (:approval_id, 'auto_created', :event_note, :created_by)
                ");
                $stmtAudit->execute([
                    ':approval_id' => $approvalId,
                    ':event_note' => 'Auto-created cash variance approval.',
                    ':created_by' => pa_current_user_id() ?: null,
                ]);
                $created++;
            }

            pa_flash('success', $created . ' cash variance approval request(s) created.');
            header('Location: pos_approvals.php?approval_type=cash_variance&status=pending');
            exit;
        }

    } catch (Throwable $e) {
        pa_flash('danger', $e->getMessage());
        header('Location: pos_approvals.php');
        exit;
    }
}

$stores = [];
try {
    $stores = $pdo->query("SELECT * FROM store_locations WHERE is_active=1 ORDER BY is_pos_location DESC, location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load stores: ' . $e->getMessage();
}

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$status = trim((string)($_GET['status'] ?? 'pending'));
$approvalType = trim((string)($_GET['approval_type'] ?? ''));
$storeId = (int)($_GET['store_id'] ?? 0);
$search = trim((string)($_GET['q'] ?? ''));

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-01');
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d');
if (strtotime($dateFrom) > strtotime($dateTo)) {
    $tmp = $dateFrom; $dateFrom = $dateTo; $dateTo = $tmp;
}

$where = "DATE(ar.created_at) BETWEEN :date_from AND :date_to";
$params = [':date_from' => $dateFrom, ':date_to' => $dateTo];

if ($status !== '') {
    $where .= " AND ar.status=:status";
    $params[':status'] = $status;
}
if ($approvalType !== '') {
    $where .= " AND ar.approval_type=:approval_type";
    $params[':approval_type'] = $approvalType;
}
if ($storeId > 0) {
    $where .= " AND ar.store_id=:store_id";
    $params[':store_id'] = $storeId;
}
if ($search !== '') {
    $where .= " AND (ar.request_no LIKE :q OR ar.reason LIKE :q OR ar.reference_type LIKE :q OR sl.location_name LIKE :q)";
    $params[':q'] = '%' . $search . '%';
}

$requesterNameExpr = pa_user_name_expr($pdo, 'req');
$approverNameExpr = pa_user_name_expr($pdo, 'app');

$requests = [];
$summary = [
    'pending' => 0,
    'approved' => 0,
    'rejected' => 0,
    'cancelled' => 0,
    'total_amount' => 0,
];

try {
    $userJoin = pa_table_exists($pdo, 'users') ? "
        LEFT JOIN users req ON req.id = ar.requested_by
        LEFT JOIN users app ON app.id = ar.approved_by
    " : "";

    $stmt = $pdo->prepare("
        SELECT
            ar.*,
            sl.location_name,
            {$requesterNameExpr} AS requested_by_name,
            {$approverNameExpr} AS approved_by_name
        FROM pos_approval_requests ar
        LEFT JOIN store_locations sl ON sl.id = ar.store_id
        {$userJoin}
        WHERE $where
        ORDER BY
            CASE ar.status WHEN 'pending' THEN 0 WHEN 'approved' THEN 1 WHEN 'rejected' THEN 2 ELSE 3 END,
            ar.created_at DESC,
            ar.id DESC
        LIMIT 700
    ");
    $stmt->execute($params);
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->query("
        SELECT status, COUNT(*) AS cnt, COALESCE(SUM(amount),0) AS amt
        FROM pos_approval_requests
        GROUP BY status
    ");
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $summary[$row['status']] = (int)$row['cnt'];
        $summary['total_amount'] += (float)$row['amt'];
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load approval requests: ' . $e->getMessage();
}

$pendingVoids = [];
$varianceShifts = [];
try {
    $stmt = $pdo->query("
        SELECT po.*, sl.location_name
        FROM pos_orders po
        LEFT JOIN store_locations sl ON sl.id = po.store_id
        WHERE po.status <> 'void'
        ORDER BY po.created_at DESC
        LIMIT 20
    ");
    $pendingVoids = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->query("
        SELECT ps.*, sl.location_name
        FROM pos_shifts ps
        LEFT JOIN store_locations sl ON sl.id = ps.store_id
        WHERE ps.status='closed'
          AND ABS(ps.variance) > 0
        ORDER BY ABS(ps.variance) DESC, ps.closed_at DESC
        LIMIT 20
    ");
    $varianceShifts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

$viewId = (int)($_GET['view_id'] ?? 0);
$viewRequest = null;
$viewAudit = [];
$viewReference = null;

if ($viewId > 0) {
    try {
        $userJoin = pa_table_exists($pdo, 'users') ? "
            LEFT JOIN users req ON req.id = ar.requested_by
            LEFT JOIN users app ON app.id = ar.approved_by
        " : "";

        $stmt = $pdo->prepare("
            SELECT
                ar.*,
                sl.location_name,
                {$requesterNameExpr} AS requested_by_name,
                {$approverNameExpr} AS approved_by_name
            FROM pos_approval_requests ar
            LEFT JOIN store_locations sl ON sl.id = ar.store_id
            {$userJoin}
            WHERE ar.id=:id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewId]);
        $viewRequest = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($viewRequest) {
            $stmt = $pdo->prepare("
                SELECT aa.*, " . pa_user_name_expr($pdo, 'u') . " AS user_name
                FROM pos_approval_audit aa
                " . (pa_table_exists($pdo, 'users') ? "LEFT JOIN users u ON u.id = aa.created_by" : "") . "
                WHERE aa.approval_id=:id
                ORDER BY aa.created_at DESC, aa.id DESC
            ");
            $stmt->execute([':id' => $viewId]);
            $viewAudit = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if ($viewRequest['reference_type'] === 'pos_order' && !empty($viewRequest['reference_id'])) {
                $stmt = $pdo->prepare("SELECT * FROM pos_orders WHERE id=:id LIMIT 1");
                $stmt->execute([':id' => (int)$viewRequest['reference_id']]);
                $viewReference = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
            } elseif ($viewRequest['reference_type'] === 'pos_shift' && !empty($viewRequest['reference_id'])) {
                $stmt = $pdo->prepare("SELECT * FROM pos_shifts WHERE id=:id LIMIT 1");
                $stmt->execute([':id' => (int)$viewRequest['reference_id']]);
                $viewReference = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
            }
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not load approval detail: ' . $e->getMessage();
    }
}

$flashes = pa_get_flash();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-shield-lock"></i> POS Controls</div>
            <div class="hero-title mt-2">Manager Approvals</div>
            <div class="hero-subtitle mt-2">
                Control voids, discounts, cash variance, stock adjustments and sensitive POS actions.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="pos.php" class="btn btn-light me-2"><i class="bi bi-cash-register me-2"></i>Open POS</a>
            <a href="pos_shifts.php" class="btn btn-outline-light"><i class="bi bi-person-badge me-2"></i>Shifts</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?> no-print"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger no-print">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<?php if ($viewRequest): ?>
<div class="card panel-card mb-4 approval-view">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0"><?php echo h($viewRequest['request_no']); ?></h5>
            <div class="small text-muted">
                <?php echo h(ucwords(str_replace('_',' ', $viewRequest['approval_type']))); ?>
                • <?php echo h($viewRequest['location_name'] ?: 'No store'); ?>
            </div>
        </div>
        <a href="pos_approvals.php" class="btn btn-sm btn-outline-secondary no-print">Close</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-4">
            <div class="col-md-3">
                <strong>Status</strong><br>
                <span class="badge <?php
                    echo $viewRequest['status'] === 'pending' ? 'text-bg-warning' :
                        ($viewRequest['status'] === 'approved' ? 'text-bg-success' :
                            ($viewRequest['status'] === 'rejected' ? 'text-bg-danger' : 'text-bg-secondary'));
                ?>">
                    <?php echo h(ucwords($viewRequest['status'])); ?>
                </span>
            </div>
            <div class="col-md-3"><strong>Amount</strong><br><?php echo money_fmt($viewRequest['amount']); ?></div>
            <div class="col-md-3"><strong>Requested By</strong><br><?php echo h($viewRequest['requested_by_name'] ?: 'User'); ?></div>
            <div class="col-md-3"><strong>Requested</strong><br><?php echo h($viewRequest['created_at']); ?></div>
        </div>

        <div class="alert alert-light border">
            <strong>Reason:</strong><br><?php echo nl2br(h($viewRequest['reason'] ?: 'No reason supplied')); ?>
        </div>

        <?php if (!empty($viewRequest['manager_comment'])): ?>
            <div class="alert alert-info">
                <strong>Manager Comment:</strong><br><?php echo nl2br(h($viewRequest['manager_comment'])); ?>
            </div>
        <?php endif; ?>

        <?php if ($viewReference): ?>
            <h6 class="fw-bold">Linked Reference</h6>
            <div class="table-responsive mb-4">
                <table class="table table-sm">
                    <tbody>
                    <?php if ($viewRequest['reference_type'] === 'pos_order'): ?>
                        <tr><th>Receipt</th><td><?php echo h($viewReference['pos_no'] ?? ''); ?></td></tr>
                        <tr><th>Total</th><td><?php echo money_fmt($viewReference['total_amount'] ?? 0); ?></td></tr>
                        <tr><th>Status</th><td><?php echo h($viewReference['status'] ?? ''); ?></td></tr>
                    <?php elseif ($viewRequest['reference_type'] === 'pos_shift'): ?>
                        <tr><th>Shift</th><td><?php echo h($viewReference['shift_no'] ?? ''); ?></td></tr>
                        <tr><th>Expected Cash</th><td><?php echo money_fmt($viewReference['expected_cash'] ?? 0); ?></td></tr>
                        <tr><th>Counted Cash</th><td><?php echo money_fmt($viewReference['counted_cash'] ?? 0); ?></td></tr>
                        <tr><th>Variance</th><td><?php echo money_fmt($viewReference['variance'] ?? 0); ?></td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <?php if ($viewRequest['status'] === 'pending'): ?>
            <div class="row g-3 no-print mb-4">
                <div class="col-lg-6">
                    <div class="approval-action approve-box">
                        <h6>Approve Request</h6>
                        <form method="post" onsubmit="return confirm('Approve this request?');">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="approve_request">
                            <input type="hidden" name="approval_id" value="<?php echo (int)$viewRequest['id']; ?>">
                            <input type="password" name="manager_password" class="form-control mb-2" placeholder="Manager password / PIN" required>
                            <input type="text" name="manager_comment" class="form-control mb-2" placeholder="Comment optional">
                            <button class="btn btn-success w-100"><i class="bi bi-check-circle me-2"></i>Approve</button>
                        </form>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="approval-action reject-box">
                        <h6>Reject Request</h6>
                        <form method="post" onsubmit="return confirm('Reject this request?');">
                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                            <input type="hidden" name="action" value="reject_request">
                            <input type="hidden" name="approval_id" value="<?php echo (int)$viewRequest['id']; ?>">
                            <input type="password" name="manager_password" class="form-control mb-2" placeholder="Manager password / PIN" required>
                            <input type="text" name="manager_comment" class="form-control mb-2" placeholder="Rejection reason" required>
                            <button class="btn btn-outline-danger w-100"><i class="bi bi-x-circle me-2"></i>Reject</button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <h6 class="fw-bold">Audit Trail</h6>
        <div class="timeline-box">
            <?php if (!$viewAudit): ?>
                <div class="text-muted">No audit events.</div>
            <?php else: foreach ($viewAudit as $ev): ?>
                <div class="timeline-item">
                    <div class="timeline-dot"></div>
                    <div>
                        <strong><?php echo h(ucwords(str_replace('_',' ', $ev['event_type']))); ?></strong>
                        <div class="small text-muted"><?php echo h($ev['created_at']); ?> • <?php echo h($ev['user_name'] ?: 'System'); ?></div>
                        <?php if (!empty($ev['event_note'])): ?><div><?php echo h($ev['event_note']); ?></div><?php endif; ?>
                    </div>
                </div>
            <?php endforeach; endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row g-4 mb-4 no-print">
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-hourglass-split"></i></div><div><div class="metric-label">Pending</div><div class="metric-value"><?php echo (int)$summary['pending']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-check-circle"></i></div><div><div class="metric-label">Approved</div><div class="metric-value"><?php echo (int)$summary['approved']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-x-circle"></i></div><div><div class="metric-label">Rejected</div><div class="metric-value"><?php echo (int)$summary['rejected']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-cash-stack"></i></div><div><div class="metric-label">Amount</div><div class="metric-value small-value"><?php echo money_fmt($summary['total_amount']); ?></div></div></div></div>
</div>

<div class="row g-4 no-print">
    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Create Approval Request</h5></div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="create_request">

                    <div class="mb-3">
                        <label class="form-label">Approval Type</label>
                        <select name="approval_type" class="form-select" required>
                            <option value="void_receipt">Void Receipt</option>
                            <option value="discount">Discount</option>
                            <option value="cash_variance">Cash Variance</option>
                            <option value="stock_adjustment">Stock Adjustment</option>
                            <option value="price_override">Price Override</option>
                            <option value="refund">Refund</option>
                            <option value="other">Other</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Store</label>
                        <select name="store_id" class="form-select">
                            <option value="0">No store / General</option>
                            <?php foreach ($stores as $store): ?>
                                <option value="<?php echo (int)$store['id']; ?>"><?php echo h($store['location_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="row g-2">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Reference Type</label>
                            <input type="text" name="reference_type" class="form-control" value="manual">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Reference ID</label>
                            <input type="number" name="reference_id" class="form-control" value="0">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Amount / Variance</label>
                        <input type="number" step="0.01" name="amount" class="form-control" value="0.00">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Reason</label>
                        <textarea name="reason" class="form-control" rows="3" required></textarea>
                    </div>

                    <button class="btn btn-primary w-100"><i class="bi bi-plus-circle me-2"></i>Create Request</button>
                </form>
            </div>
        </div>

        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Auto Create Variance Approvals</h5></div>
            <div class="card-body">
                <form method="post">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="auto_create_variance_requests">
                    <label class="form-label">Minimum Variance</label>
                    <input type="number" step="0.01" name="threshold" class="form-control mb-3" value="5.00">
                    <button class="btn btn-outline-warning w-100"><i class="bi bi-magic me-2"></i>Create from Closed Shifts</button>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Variance Shifts</h5></div>
            <div class="card-body p-0">
                <table class="table table-modern mb-0">
                    <thead><tr><th>Shift</th><th>Store</th><th class="text-end">Variance</th></tr></thead>
                    <tbody>
                    <?php if (!$varianceShifts): ?>
                        <tr><td colspan="3" class="text-center text-muted py-4">No variance shifts.</td></tr>
                    <?php else: foreach ($varianceShifts as $shift): ?>
                        <tr>
                            <td><a href="pos_shifts.php?view_id=<?php echo (int)$shift['id']; ?>"><strong><?php echo h($shift['shift_no']); ?></strong></a></td>
                            <td><?php echo h($shift['location_name'] ?: 'Store'); ?></td>
                            <td class="text-end fw-bold <?php echo (float)$shift['variance'] != 0 ? 'text-danger' : 'text-success'; ?>"><?php echo money_fmt($shift['variance']); ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-2"><label class="form-label">From</label><input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>"></div>
                    <div class="col-md-2"><label class="form-label">To</label><input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>"></div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="approved" <?php echo $status === 'approved' ? 'selected' : ''; ?>>Approved</option>
                            <option value="rejected" <?php echo $status === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                            <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Type</label>
                        <select name="approval_type" class="form-select">
                            <option value="">All</option>
                            <?php foreach (['void_receipt'=>'Void Receipt','discount'=>'Discount','cash_variance'=>'Cash Variance','stock_adjustment'=>'Stock Adjustment','price_override'=>'Price Override','refund'=>'Refund','other'=>'Other'] as $v=>$l): ?>
                                <option value="<?php echo h($v); ?>" <?php echo $approvalType === $v ? 'selected' : ''; ?>><?php echo h($l); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Store</label>
                        <select name="store_id" class="form-select">
                            <option value="0">All</option>
                            <?php foreach ($stores as $store): ?>
                                <option value="<?php echo (int)$store['id']; ?>" <?php echo $storeId === (int)$store['id'] ? 'selected' : ''; ?>><?php echo h($store['location_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-1"><label class="form-label">Search</label><input type="text" name="q" class="form-control" value="<?php echo h($search); ?>"></div>
                    <div class="col-md-1 d-grid"><button class="btn btn-primary"><i class="bi bi-funnel"></i></button></div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Approval Requests</h5>
                <span class="text-muted small">Showing latest 700 requests</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Request</th>
                            <th>Type</th>
                            <th>Store</th>
                            <th>Requested By</th>
                            <th>Status</th>
                            <th class="text-end">Amount</th>
                            <th>Reason</th>
                            <th class="text-end">Action</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$requests): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No approval requests found.</td></tr>
                        <?php else: foreach ($requests as $req): ?>
                            <tr class="<?php echo $req['status'] === 'pending' ? 'table-warning' : ''; ?>">
                                <td>
                                    <strong><?php echo h($req['request_no']); ?></strong>
                                    <div class="small text-muted"><?php echo h(date('Y-m-d H:i', strtotime($req['created_at']))); ?></div>
                                </td>
                                <td><?php echo h(ucwords(str_replace('_',' ', $req['approval_type']))); ?></td>
                                <td><?php echo h($req['location_name'] ?: '—'); ?></td>
                                <td><?php echo h($req['requested_by_name'] ?: 'User'); ?></td>
                                <td>
                                    <span class="badge <?php
                                        echo $req['status'] === 'pending' ? 'text-bg-warning' :
                                            ($req['status'] === 'approved' ? 'text-bg-success' :
                                                ($req['status'] === 'rejected' ? 'text-bg-danger' : 'text-bg-secondary'));
                                    ?>">
                                        <?php echo h(ucwords($req['status'])); ?>
                                    </span>
                                </td>
                                <td class="text-end fw-bold"><?php echo money_fmt($req['amount']); ?></td>
                                <td class="small"><?php echo h(mb_strimwidth((string)$req['reason'], 0, 80, '...')); ?></td>
                                <td class="text-end">
                                    <a href="pos_approvals.php?view_id=<?php echo (int)$req['id']; ?>" class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card panel-card mt-4">
            <div class="card-header"><h5 class="mb-0">Recent Receipts for Void Approval</h5></div>
            <div class="card-body p-0">
                <table class="table table-modern mb-0">
                    <thead><tr><th>Receipt</th><th>Store</th><th>Status</th><th class="text-end">Total</th><th class="text-end">Create</th></tr></thead>
                    <tbody>
                    <?php if (!$pendingVoids): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">No receipts found.</td></tr>
                    <?php else: foreach ($pendingVoids as $po): ?>
                        <tr>
                            <td><a href="pos_orders.php?view_id=<?php echo (int)$po['id']; ?>"><strong><?php echo h($po['pos_no']); ?></strong></a><div class="small text-muted"><?php echo h($po['created_at']); ?></div></td>
                            <td><?php echo h($po['location_name'] ?: 'Store'); ?></td>
                            <td><?php echo h($po['status']); ?></td>
                            <td class="text-end fw-bold"><?php echo money_fmt($po['total_amount']); ?></td>
                            <td class="text-end">
                                <form method="post" class="d-inline">
                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                    <input type="hidden" name="action" value="create_request">
                                    <input type="hidden" name="approval_type" value="void_receipt">
                                    <input type="hidden" name="reference_type" value="pos_order">
                                    <input type="hidden" name="reference_id" value="<?php echo (int)$po['id']; ?>">
                                    <input type="hidden" name="store_id" value="<?php echo (int)$po['store_id']; ?>">
                                    <input type="hidden" name="amount" value="<?php echo h($po['total_amount']); ?>">
                                    <input type="hidden" name="reason" value="Void approval requested for receipt <?php echo h($po['pos_no']); ?>">
                                    <button class="btn btn-sm btn-outline-danger">Request Void</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.approval-view{border:2px solid rgba(37,99,235,.18)}
.approval-action{border:1px solid rgba(15,23,42,.10);border-radius:18px;padding:14px}
.approve-box{background:#ecfdf5;border-color:#bbf7d0}
.reject-box{background:#fff7ed;border-color:#fed7aa}
.timeline-box{display:flex;flex-direction:column;gap:12px}
.timeline-item{display:grid;grid-template-columns:16px 1fr;gap:10px}
.timeline-dot{width:12px;height:12px;border-radius:50%;background:#2563eb;margin-top:5px}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    .panel-card,.card,.metric-card{box-shadow:none!important}
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
