<?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, section_name, id_number, name, signature, pass_date, pass_time, reason, date_time_filed, status
             FROM employee_passes
             ORDER BY id DESC'
        );

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

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

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

        $sectionName = clean_text($_POST['section_name'] ?? '');
        $idNumber = clean_text($_POST['id_number'] ?? '');
        $name = title_case_text($_POST['name'] ?? '');
        $signature = title_case_text($_POST['signature'] ?? '');
        $passDate = clean_text($_POST['pass_date'] ?? '');
        $passTime = clean_text($_POST['pass_time'] ?? '');
        $reason = clean_text($_POST['reason'] ?? '');

        if (
            $sectionName === '' ||
            $idNumber === '' ||
            $name === '' ||
            $passDate === '' ||
            $passTime === '' ||
            $reason === ''
        ) {
            json_response([
                'success' => false,
                'message' => 'Section, ID No., name, date, time, and reason are required.'
            ], 422);
        }

        if ($signature === '') {
            $signature = $name;
        }

        if ($id > 0) {
            db_execute(
                $conn,
                'UPDATE employee_passes
                 SET section_name = ?,
                     id_number = ?,
                     name = ?,
                     signature = ?,
                     pass_date = ?,
                     pass_time = ?,
                     reason = ?
                 WHERE id = ?',
                'sssssssi',
                [
                    $sectionName,
                    $idNumber,
                    $name,
                    $signature,
                    $passDate,
                    $passTime,
                    $reason,
                    $id
                ]
            );

            log_activity($conn, 'Update Personnel Pass', "Personnel {$idNumber} was updated.");
        } else {
            $createdBy = current_user()['id'] ?? null;
            $dateTimeFiled = date('Y-m-d H:i:s');
            $status = 'Pending';
            $transactionRef = generate_transaction_ref();

            db_execute(
                $conn,
                'INSERT INTO employee_passes
                    (
                        transaction_ref,
                        section_name,
                        id_number,
                        name,
                        signature,
                        pass_date,
                        pass_time,
                        reason,
                        date_time_filed,
                        status,
                        created_by
                    )
                 VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                'ssssssssssi',
                [
                    $transactionRef,
                    $sectionName,
                    $idNumber,
                    $name,
                    $signature,
                    $passDate,
                    $passTime,
                    $reason,
                    $dateTimeFiled,
                    $status,
                    $createdBy
                ]
            );

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

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

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

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

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

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

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

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