<?php

require_once __DIR__ . '/helpers.php';

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

function log_public_activity(mysqli $conn, string $action, string $details): void
{
    db_execute(
        $conn,
        'INSERT INTO activity_logs (action, details) VALUES (?, ?)',
        'ss',
        [$action, $details]
    );
}

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response([
            'success' => false,
            'message' => 'Invalid request.'
        ], 405);
    }

    $action = clean_text($_POST['action'] ?? '');
    $passType = clean_text($_POST['pass_type'] ?? '');
    $status = 'Pending';

    if ($action !== 'create') {
        json_response([
            'success' => false,
            'message' => 'Invalid request.'
        ], 400);
    }

    /*
    |--------------------------------------------------------------------------
    | PERSONNEL PASS
    |--------------------------------------------------------------------------
    */

    if ($passType === 'personnel') {

        $transactionRef = generate_transaction_ref();

        $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' => 'Please complete all required personnel fields.'
            ], 422);
        }

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

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

        log_public_activity(
            $conn,
            'Create Personnel Pass',
            "Public personnel {$idNumber} was submitted. Ref: {$transactionRef}"
        );

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

    /*
    |--------------------------------------------------------------------------
    | VISITOR PASS
    |--------------------------------------------------------------------------
    */

    if ($passType === 'visitor') {

        $transactionRef = generate_transaction_ref();

        $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' => 'Please complete all required visitor fields.'
            ], 422);
        }

        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
            )
            VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)',
            'ssssssssss',
            [
                $transactionRef,
                $visitorName,
                $visitDate,
                $timeIn,
                $timeOut,
                $personToVisit,
                $sectionName,
                $purpose,
                $otherPurpose,
                $status
            ]
        );

        log_public_activity(
            $conn,
            'Create Visitor Pass',
            "Public visitor {$visitorName} was submitted. Ref: {$transactionRef}"
        );

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

    /*
    |--------------------------------------------------------------------------
    | ITEM PASS
    |--------------------------------------------------------------------------
    */

    if ($passType === 'item') {

        $transactionRef = generate_transaction_ref();

        $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' => 'Please complete all required item fields.'
            ], 422);
        }

        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
            ]
        );

        log_public_activity(
            $conn,
            'Create Item Pass',
            "Public item pass was submitted. Ref: {$transactionRef}"
        );

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

    /*
    |--------------------------------------------------------------------------
    | FOOD PASS
    |--------------------------------------------------------------------------
    */

    if ($passType === 'food') {

        $transactionRef = generate_transaction_ref();

        $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' => 'Please complete all required food fields.'
            ], 422);
        }

        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
            ]
        );

        log_public_activity(
            $conn,
            'Create Food Pass',
            "Public food pass was submitted. Ref: {$transactionRef}"
        );

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

    /*
    |--------------------------------------------------------------------------
    | MEAL BREAK PASS
    |--------------------------------------------------------------------------
    */

    if ($passType === 'mealbreak') {

        $transactionRef = generate_transaction_ref();

        $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' => 'Please complete all required meal break fields.'
            ], 422);
        }

        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
            ]
        );

        log_public_activity(
            $conn,
            'Create Meal Break Pass',
            "Public meal break pass was submitted. Ref: {$transactionRef}"
        );

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

    json_response([
        'success' => false,
        'message' => 'Choose a valid pass type.'
    ], 422);

} catch (Throwable $e) {

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