<?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,
                visitor_name,
                visit_date,
                time_in,
                time_out,
                person_to_visit,
                section_name,
                purpose,
                other_purpose,
                date_submitted,
                status
             FROM visitor_passes
             ORDER BY id DESC'
        );

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

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

    if ($action === 'save') {

        $id = (int) ($_POST['id'] ?? 0);

        $visitorName = title_case_text($_POST['visitor_name'] ?? '');

        $visitDate = clean_text($_POST['visit_date'] ?? '');

        $timeIn = clean_text($_POST['time_in'] ?? '');

        $timeOut = clean_text($_POST['time_out'] ?? '');

        $personToVisit = title_case_text($_POST['person_to_visit'] ?? '');

        $sectionName = clean_text($_POST['section_name'] ?? '');

        $purpose = clean_text($_POST['purpose'] ?? '');

        $otherPurpose = clean_text($_POST['other_purpose'] ?? '');

        if (
            $visitorName === '' ||
            $visitDate === '' ||
            $timeIn === '' ||
            $timeOut === '' ||
            $personToVisit === '' ||
            $sectionName === '' ||
            $purpose === ''
        ) {

            json_response([
                'success' => false,
                'message' => 'All fields are required.'
            ], 422);
        }

        if ($id > 0) {

            db_execute(
                $conn,
                'UPDATE visitor_passes
                 SET visitor_name = ?,
                     visit_date = ?,
                     time_in = ?,
                     time_out = ?,
                     person_to_visit = ?,
                     section_name = ?,
                     purpose = ?,
                     other_purpose = ?
                 WHERE id = ?',
                'ssssssssi',
                [
                    $visitorName,
                    $visitDate,
                    $timeIn,
                    $timeOut,
                    $personToVisit,
                    $sectionName,
                    $purpose,
                    $otherPurpose,
                    $id
                ]
            );

            log_activity(
                $conn,
                'Update Visitor Pass',
                "Visitor {$visitorName} was updated."
            );

        } else {

            $createdBy = current_user()['id'] ?? null;

            $dateSubmitted = date('Y-m-d H:i:s');

            $status = 'Pending';

            $transactionRef = generate_transaction_ref();

            db_execute(
                $conn,
                'INSERT INTO visitor_passes
                (
                    transaction_ref,
                    visitor_name,
                    visit_date,
                    time_in,
                    time_out,
                    person_to_visit,
                    section_name,
                    purpose,
                    other_purpose,
                    date_submitted,
                    status,
                    created_by
                )
                VALUES
                (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                'sssssssssssi',
                [
                    $transactionRef,
                    $visitorName,
                    $visitDate,
                    $timeIn,
                    $timeOut,
                    $personToVisit,
                    $sectionName,
                    $purpose,
                    $otherPurpose,
                    $dateSubmitted,
                    $status,
                    $createdBy
                ]
            );
            db_execute(
    $conn,
    'INSERT INTO notifications
    (pass_type, transaction_ref, message)
    VALUES (?, ?, ?)',
    'sss',
    [
        'Visitor Pass',
        $transactionRef,
        '🚶 New Visitor Pass Request Received. Click the bell icon to review.'
    ]
);

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

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

    if ($action === 'delete') {

        $id = (int) ($_POST['id'] ?? 0);

        if ($id <= 0) {

            json_response([
                'success' => false,
                'message' => 'Invalid visitor pass.'
            ], 422);
        }

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

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

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