<?php

require_once __DIR__ . '/helpers.php';
api_require_login();

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response(['success' => false, 'message' => 'Invalid request.'], 405);
    }

    $transactionRef = clean_text($_POST['transaction_ref'] ?? '');

    if ($transactionRef === '') {
        json_response(['success' => false, 'message' => 'Transaction reference is required.'], 422);
    }

    $tables = [
        [
            'table' => 'employee_passes',
            'type' => 'Personnel Pass',
            'name_field' => 'name',
            'date_field' => 'pass_date'
        ],
        [
            'table' => 'visitor_passes',
            'type' => 'Visitor Pass',
            'name_field' => 'visitor_name',
            'date_field' => 'visit_date'
        ],
        [
            'table' => 'package_passes',
            'type' => 'Item Pass',
            'name_field' => 'description',
            'date_field' => 'created_at'
        ],
        [
            'table' => 'item_passes',
            'type' => 'Food Pass',
            'name_field' => 'food_items',
            'date_field' => 'created_at'
        ],
        [
            'table' => 'meal_break_passes',
            'type' => 'Meal Break Pass',
            'name_field' => 'name',
            'date_field' => 'created_at'
        ],
    ];

    foreach ($tables as $item) {
        $row = db_one(
            $conn,
            "SELECT 
                transaction_ref,
                {$item['name_field']} AS main_name,
                {$item['date_field']} AS pass_date,
                status
             FROM {$item['table']}
             WHERE transaction_ref = ?
             LIMIT 1",
            's',
            [$transactionRef]
        );

        if ($row) {
            $row['pass_type'] = $item['type'];

            log_activity(
                $conn,
                'Scan Gatepass QR',
                "Scanned {$transactionRef} ({$item['type']})."
            );

            json_response([
                'success' => true,
                'data' => $row
            ]);
        }
    }

    json_response([
        'success' => false,
        'message' => 'No pass found for this QR code.'
    ], 404);

} catch (Throwable $e) {
    json_response([
        'success' => false,
        'message' => 'Scan failed. Please try again.'
    ], 500);
}