<?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, name, line_section, time_out, time_in, purpose, status
             FROM meal_break_passes
             ORDER BY id DESC'
        );

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

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

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

        $name = title_case_text($_POST['name'] ?? '');
        $lineSection = clean_text($_POST['line_section'] ?? '');
        $timeOut = clean_text($_POST['time_out'] ?? '');
        $timeIn = clean_text($_POST['time_in'] ?? '');
        $purpose = title_case_text($_POST['purpose'] ?? '');

        if ($name === '' || $lineSection === '' || $timeOut === '' || $timeIn === '' || $purpose === '') {
            json_response([
                'success' => false,
                'message' => 'Name, line/section, time out, time in, and purpose are required.'
            ], 422);
        }

        if ($id > 0) {
            db_execute(
                $conn,
                'UPDATE meal_break_passes
                 SET name = ?,
                     line_section = ?,
                     time_out = ?,
                     time_in = ?,
                     purpose = ?
                 WHERE id = ?',
                'sssssi',
                [$name, $lineSection, $timeOut, $timeIn, $purpose, $id]
            );

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

            db_execute(
                $conn,
                'INSERT INTO meal_break_passes
                    (transaction_ref, name, line_section, time_out, time_in, purpose, status)
                 VALUES
                    (?, ?, ?, ?, ?, ?, ?)',
                'sssssss',
                [$transactionRef, $name, $lineSection, $timeOut, $timeIn, $purpose, $status]
            );

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

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

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

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

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

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

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

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