<?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, food_items, quantity_measurement, container_type, reason, status
             FROM item_passes
             ORDER BY id DESC'
        );

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

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

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

        $foodItems = title_case_text($_POST['food_items'] ?? '');
        $quantityMeasurement = clean_text($_POST['quantity_measurement'] ?? '');
        $containerType = title_case_text($_POST['container_type'] ?? '');
        $reason = title_case_text($_POST['reason'] ?? '');

        if (
            $foodItems === '' ||
            $quantityMeasurement === '' ||
            $containerType === '' ||
            $reason === ''
        ) {
            json_response([
                'success' => false,
                'message' => 'Food items, quantity/measurement, container type, and reason are required.'
            ], 422);
        }

        if ($id > 0) {
            db_execute(
                $conn,
                'UPDATE item_passes
                 SET food_items = ?,
                     quantity_measurement = ?,
                     container_type = ?,
                     reason = ?
                 WHERE id = ?',
                'ssssi',
                [
                    $foodItems,
                    $quantityMeasurement,
                    $containerType,
                    $reason,
                    $id
                ]
            );

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

            db_execute(
                $conn,
                'INSERT INTO item_passes
                    (
                        transaction_ref,
                        food_items,
                        quantity_measurement,
                        container_type,
                        reason,
                        status
                    )
                 VALUES
                    (?, ?, ?, ?, ?, ?)',
                'ssssss',
                [
                    $transactionRef,
                    $foodItems,
                    $quantityMeasurement,
                    $containerType,
                    $reason,
                    $status
                ]
            );

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

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

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

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

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

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

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

        json_response(['success' => true, 'message' => 'Food 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);
}