<?php
// searchPermit.php
require_once('../config/dbConnection.php');
header('Content-Type: application/json');

// Check if 'application_number' param exists and is not empty
if (!isset($_GET['application_number']) || strlen(trim($_GET['application_number'])) === 0) {
    echo json_encode([]);
    exit;
}

$application_number = trim($_GET['application_number']);

// Get DB connection instance
$db = DatabaseConnection::getInstance();
$conn = $db->getConnection();

// Prepare and execute query using LIKE with wildcard at the end
$stmt = $conn->prepare("
    SELECT
        application_number,
        business_name,
        owner_name,
        business_type,
        receipt_number,
        location,
        street,
        phone_number,
        status,
        entry_type,
        permit_type,
        submitted_at,
        owner_email,
        qr_code,
        attachment,
        nrc,
        comment,
        approved_by,
        approved_date,
        business_category_id,
        blevy_amount,
        firecert_amount,
        healthpermit_amount,
        audited_by,
        verified_by,
        employee_no,
        notified
    FROM permits
    WHERE application_number LIKE CONCAT(?, '%')
    LIMIT 20
");

$stmt->bind_param('s', $application_number);
$stmt->execute();

$result = $stmt->get_result();

$permits = [];
while ($row = $result->fetch_assoc()) {
    $permits[] = $row;
}

echo json_encode($permits);
exit;
