<?php
session_start();

require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/trips.php';

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['authenticated'])) {
    echo json_encode(['success' => false, 'users' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$userId = current_user_id();
if ($userId <= 0) {
    echo json_encode(['success' => false, 'users' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

trip_ensure_schema();

$organizationRow = fetch_one(
    'SELECT id
     FROM organizations
     WHERE user_id = ?
       AND is_deleted = 0
     ORDER BY id DESC
     LIMIT 1',
    'i',
    [$userId]
);
$organizationId = (int) ($organizationRow['id'] ?? 0);
$query = trim((string) ($_GET['q'] ?? ''));
$search = '%' . $query . '%';

$sql = 'SELECT
            a.approver_record_id AS id,
            a.approver_user_id,
            COALESCE(
                NULLIF(TRIM(tp.passport_name), ""),
                NULLIF(TRIM(CONCAT_WS(" ", tp.first_name, tp.middle_name, tp.last_name)), ""),
                NULLIF(TRIM(a.approver_name), ""),
                NULLIF(TRIM(u.business_name), ""),
                NULLIF(TRIM(u.email), ""),
                "Expense user"
            ) AS display_name,
            COALESCE(
                NULLIF(TRIM(tp.personal_email), ""),
                NULLIF(TRIM(a.approver_email), ""),
                NULLIF(TRIM(u.email), "")
            ) AS email,
            COALESCE(NULLIF(TRIM(tp.profile_photo_path), ""), NULLIF(TRIM(a.profile_photo_path), "")) AS profile_photo_path,
            COALESCE(NULLIF(TRIM(p.employee_id), ""), a.employee_id, CONCAT("ID-", LPAD(u.id, 4, "0"))) AS employee_id,
            a.source_priority,
            a.is_primary
        FROM vw_trip_submit_approvers a
        JOIN users u
          ON u.id = a.approver_user_id
        LEFT JOIN user_profiles p
          ON p.user_id = u.id
         AND p.organization_id = a.organization_id
         AND p.is_deleted = 0
         AND p.deleted_at IS NULL
        LEFT JOIN user_travel_profiles tp
          ON tp.user_id = u.id
         AND tp.organization_id = a.organization_id
         AND tp.status = "active"
         AND tp.is_deleted = 0
         AND tp.deleted_at IS NULL
        WHERE ';

if ($organizationId > 0) {
    $sql .= 'a.organization_id = ?';
    $params = [$organizationId];
    $types = 'i';
} else {
    $sql .= 'a.approver_user_id = ?';
    $params = [$userId];
    $types = 'i';
}

if ($query !== '') {
    $sql .= ' AND (
        a.approver_name LIKE ?
        OR a.approver_email LIKE ?
        OR a.employee_id LIKE ?
        OR u.business_name LIKE ?
        OR u.email LIKE ?
        OR p.employee_id LIKE ?
        OR tp.passport_name LIKE ?
        OR tp.first_name LIKE ?
        OR tp.middle_name LIKE ?
        OR tp.last_name LIKE ?
        OR tp.personal_email LIKE ?
    )';
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $types .= 'sssssssssss';
}

$sql .= ' ORDER BY a.source_priority ASC, a.is_primary DESC, display_name ASC, a.approver_record_id DESC LIMIT 25';

$rows = fetch_all($sql, $types, $params);
$users = [];

foreach ($rows as $row) {
    $name = trim((string) ($row['display_name'] ?? ''));
    $email = trim((string) ($row['email'] ?? ''));
    $photo = trim((string) ($row['profile_photo_path'] ?? ''));
    $employeeId = trim((string) ($row['employee_id'] ?? ''));

    $users[] = [
        'id' => (int) ($row['id'] ?? 0),
        'approver_user_id' => (int) ($row['approver_user_id'] ?? 0),
        'email' => $email,
        'business_name' => $name,
        'display_name' => $name,
        'profile_photo_path' => $photo,
        'avatar_url' => trip_approver_avatar(['approver_photo_path' => $photo]),
        'employee_id' => $employeeId,
        'search' => strtolower(trim($name . ' ' . $email . ' ' . $employeeId)),
    ];
}

echo json_encode([
    'success' => true,
    'users' => $users,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
