<?php

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

function generate_transaction_ref(): string
{
    return 'GP-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $rows = db_all(
            $conn,
            'SELECT id, transaction_ref, description, quantity, measurement, remarks, checked_out, checked_in, status
             FROM package_passes
             ORDER BY id DESC'
        );

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

    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $id = (int) ($_POST['id'] ?? 0);

        $description = title_case_text($_POST['description'] ?? '');
        $quantity = (int) ($_POST['quantity'] ?? 0);
        $measurement = clean_text($_POST['measurement'] ?? '');
        $remarks = title_case_text($_POST['remarks'] ?? '');
        $checkedOut = title_case_text($_POST['checked_out'] ?? '');
        $checkedIn = title_case_text($_POST['checked_in'] ?? '');

        if ($description === '' || $quantity <= 0 || $measurement === '') {
            json_response([
                'success' => false,
                'message' => 'Description, quantity, and measurement are required.'
            ], 422);
        }

        if ($id > 0) {
            db_execute(
                $conn,
                'UPDATE package_passes
                 SET description = ?,
                     quantity = ?,
                     measurement = ?,
                     remarks = ?,
                     checked_out = ?,
                     checked_in = ?
                 WHERE id = ?',
                'sissssi',
                [
                    $description,
                    $quantity,
                    $measurement,
                    $remarks,
                    $checkedOut,
                    $checkedIn,
                    $id
                ]
            );

            log_activity($conn, 'Update Item Pass', "Item pass #{$id} was updated.");
        } else {
            $status = 'Pending';
            $transactionRef = generate_transaction_ref();

            db_execute(
                $conn,
                'INSERT INTO package_passes
                    (
                        transaction_ref,
                        description,
                        quantity,
                        measurement,
                        remarks,
                        checked_out,
                        checked_in,
                        status
                    )
                 VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?)',
                'ssisssss',
                [
                    $transactionRef,
                    $description,
                    $quantity,
                    $measurement,
                    $remarks,
                    $checkedOut,
                    $checkedIn,
                    $status
                ]
            );

            db_execute(
                $conn,
                'INSERT INTO notifications
                    (pass_type, transaction_ref, message)
                 VALUES
                    (?, ?, ?)',
                'sss',
                [
                    'Item Pass',
                    $transactionRef,
                    '📦 New Item Pass Request Received. Click the bell icon to review.'
                ]
            );

            log_activity($conn, 'Create Item Pass', "Item pass was created. Ref: {$transactionRef}");
        }

        json_response(['success' => true, 'message' => 'Item pass saved.']);
    }

    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);

        if ($id <= 0) {
            json_response(['success' => false, 'message' => 'Invalid item pass.'], 422);
        }

        db_execute($conn, 'DELETE FROM package_passes WHERE id = ?', 'i', [$id]);

        log_activity($conn, 'Delete Item Pass', "Item pass #{$id} was deleted.");

        json_response(['success' => true, 'message' => 'Item pass deleted.']);
    }

    json_response(['success' => false, 'message' => 'Invalid request.'], 400);

} catch (Throwable $e) {
    json_response([
        'success' => false,
        'message' => 'Request failed. Check your data and try again.'
    ], 500);
}