<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Agents';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('agent_full_name')) {
    function agent_full_name(array $row): string
    {
        return trim((string)($row['firstname'] ?? ''));
    }
}

if (!function_exists('hash_agent_password')) {
    function hash_agent_password(string $password): string
    {
        return sha1($password);
    }
}


if (!function_exists('agents_table_exists')) {
    function agents_table_exists(PDO $pdo, string $table): bool
    {
        static $cache = [];
        if (array_key_exists($table, $cache)) return $cache[$table];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table_name");
            $stmt->execute([':table_name' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}

if (!function_exists('agents_column_exists')) {
    function agents_column_exists(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) return $cache[$key];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table_name AND COLUMN_NAME = :column_name");
            $stmt->execute([':table_name' => $table, ':column_name' => $column]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}

if (!function_exists('agents_ensure_group_rate_column')) {
    /*
       Self-healing schema: add agents.group_rate_plan_id if it's missing.
       This mirrors agents.rate_plan_id (the agent's standard contract) but is
       resolved instead when a booking qualifies as a GROUP, so a single agent
       can hold both an FIT/standard contract and a separate group contract.
       Non-fatal: if the ALTER fails (e.g. no DDL rights) the page simply runs
       without the group field, exactly as before.
    */
    function agents_ensure_group_rate_column(PDO $pdo): bool
    {
        static $done = null;
        if ($done !== null) {
            return $done;
        }
        if (!agents_table_exists($pdo, 'agents')) {
            return $done = false;
        }
        if (agents_column_exists($pdo, 'agents', 'group_rate_plan_id')) {
            return $done = true;
        }
        try {
            $after = agents_column_exists($pdo, 'agents', 'rate_plan_id') ? ' AFTER `rate_plan_id`' : '';
            $pdo->exec("ALTER TABLE `agents` ADD COLUMN `group_rate_plan_id` INT NULL{$after}");
            // Bust the column cache so later checks see the new column.
            return $done = agents_column_exists_fresh($pdo, 'agents', 'group_rate_plan_id');
        } catch (Throwable $e) {
            return $done = false;
        }
    }
}

if (!function_exists('agents_column_exists_fresh')) {
    /* Uncached column check — used right after a DDL change. */
    function agents_column_exists_fresh(PDO $pdo, string $table, string $column): bool
    {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :t AND COLUMN_NAME = :c");
            $stmt->execute([':t' => $table, ':c' => $column]);
            return ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('fetch_countries')) {
    function fetch_countries(PDO $pdo): array
    {
        if (!agents_table_exists($pdo, 'countries')) return [];
        $stmt = $pdo->query("
            SELECT id, name
            FROM countries
            ORDER BY  name ASC
        ");
        return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
    }
}

if (!function_exists('fetch_states_by_country')) {
    function fetch_states_by_country(PDO $pdo, int $countryId): array
    {
        if ($countryId <= 0 || !agents_table_exists($pdo, 'states')) {
            return [];
        }

        $stmt = $pdo->prepare("
            SELECT id, name
            FROM states
            WHERE country_id = :country_id
            ORDER BY name ASC
        ");
        $stmt->execute([':country_id' => $countryId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

if (!function_exists('fetch_cities_by_state')) {
    function fetch_cities_by_state(PDO $pdo, int $stateId): array
    {
        if ($stateId <= 0 || !agents_table_exists($pdo, 'cities')) {
            return [];
        }

        $stmt = $pdo->prepare("
            SELECT id, name
            FROM cities
            WHERE state_id = :state_id
            ORDER BY name ASC
        ");
        $stmt->execute([':state_id' => $stateId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

/* Resolve schema capabilities before POST/AJAX handling.
   The previous page defined these much later, after the save block, which
   meant contract selections could be ignored during save. */
$hasRatePlans = agents_table_exists($pdo, 'rate_plans');
$hasAgentRateLink = $hasRatePlans && agents_column_exists($pdo, 'agents', 'rate_plan_id');
$hasRateContracts = agents_table_exists($pdo, 'rate_contracts')
    && $hasRatePlans
    && agents_column_exists($pdo, 'rate_plans', 'contract_id')
    && agents_column_exists($pdo, 'agents', 'rate_contract_id');
$hasAgentGroupContractLink = $hasRateContracts
    && agents_column_exists($pdo, 'agents', 'group_rate_contract_id');
if ($hasRatePlans) {
    agents_ensure_group_rate_column($pdo);
}
$hasAgentGroupRateLink = $hasRatePlans
    && agents_column_exists_fresh($pdo, 'agents', 'group_rate_plan_id');

$form = [
    'id'         => 0,
    'firstname'  => '',
    'lastname'   => '',
    'gender'     => '0',
    'office'     => '',
    'email'      => '',
    'password'   => '',
    'country_id' => '',
    'state_id'   => '',
    'city_id'    => '',
    'address'    => '',
    'mobile'     => '',
    'id_type'    => '',
    'id_no'      => '',
    'id_upload'  => '',
    'remark'     => '',
    'vip'        => '0',
    'order_no'   => '1',
    'dob'        => '',
    'vatno'      => '',
    'tinno'      => '',
    'phone'      => '',
    'contact'    => '',
    'payment_type' => 'on_account',
    'rate_plan_id' => '',
    'group_rate_plan_id' => '',
    'rate_contract_id' => '',
    'group_rate_contract_id' => '',
];

if (!function_exists('agents_contract_id_for_plan')) {
    /**
     * The contract a legacy rate_plans link belongs to. Used on the edit form
     * so an agent whose rate_contract_id was never populated still shows the
     * right contract selected, rather than silently reverting to rack.
     */
    function agents_contract_id_for_plan(PDO $pdo, $planId)
    {
        if ($planId === '' || (int)$planId <= 0) return '';
        try {
            $stmt = $pdo->prepare("SELECT contract_id FROM rate_plans WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => (int)$planId]);
            $cid = $stmt->fetchColumn();
            return $cid ? (string)(int)$cid : '';
        } catch (Throwable $e) {
            return '';
        }
    }
}

if (!function_exists('agents_plan_id_for_contract')) {
    /**
     * The representative rate_plans row for a contract, used to keep the
     * legacy agents.rate_plan_id link in step with agents.rate_contract_id.
     *
     * This value does NOT decide the meal plan of a booking. Pricing resolves
     * agent -> contract -> the plan whose meal_plan matches the booking. This
     * only keeps the old scalar column pointing somewhere sane for the
     * fallback path.
     */
    function agents_plan_id_for_contract(PDO $pdo, $contractId)
    {
        if ($contractId === '' || (int)$contractId <= 0) return '';
        try {
            $stmt = $pdo->prepare("
                SELECT id FROM rate_plans
                WHERE contract_id = :cid AND status = 1
                ORDER BY (meal_plan = 'BB') DESC, id ASC
                LIMIT 1");
            $stmt->execute([':cid' => (int)$contractId]);
            $id = $stmt->fetchColumn();
            return $id ? (string)(int)$id : '';
        } catch (Throwable $e) {
            return '';
        }
    }
}

$errors = [];
$success = '';
$editing = false;

// Rate contract shown on the edit form (populated only when editing an agent
// that is assigned to a plan).
$editRatePlanId    = null;
$editRatePlanTitle = '';
$editRatePlanCode  = '';

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $success = 'Agent saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'Agent deleted successfully.';
}
if (isset($_GET['delete_blocked']) && (int)$_GET['delete_blocked'] === 1) {
    $bookingCount = max(0, (int)($_GET['booking_count'] ?? 0));
    $errors[] = 'This agent cannot be deleted because '
        . $bookingCount . ' booking' . ($bookingCount === 1 ? ' is' : 's are')
        . ' linked to it in the orders table.';
}
if (isset($_GET['delete_error']) && (int)$_GET['delete_error'] === 1) {
    $errors[] = 'The agent could not be deleted. Please try again or check the database relationship.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_agent'])) {
    $form['id']         = (int)($_POST['id'] ?? 0);
    $form['firstname']  = trim((string)($_POST['firstname'] ?? ''));
    $form['lastname']   = trim((string)($_POST['lastname'] ?? ''));
    if ($form['lastname'] === '') { $form['lastname'] = $form['firstname']; }
    $form['gender']     = (string)((int)($_POST['gender'] ?? 0));
    $form['office']     = trim((string)($_POST['office'] ?? ''));
    $form['email']      = trim((string)($_POST['email'] ?? ''));
    $form['password']   = (string)($_POST['password'] ?? '');
    $form['country_id'] = trim((string)($_POST['country_id'] ?? ''));
    $form['state_id']   = trim((string)($_POST['state_id'] ?? ''));
    $form['city_id']    = trim((string)($_POST['city_id'] ?? ''));
    $form['address']    = trim((string)($_POST['address'] ?? ''));
    $form['mobile']     = trim((string)($_POST['mobile'] ?? ''));
    $form['id_type']    = trim((string)($_POST['id_type'] ?? ''));
    $form['id_no']      = trim((string)($_POST['id_no'] ?? ''));
    $form['id_upload']  = trim((string)($_POST['id_upload'] ?? ''));
    $form['remark']     = trim((string)($_POST['remark'] ?? ''));
    $form['vip']        = (string)((int)($_POST['vip'] ?? 0));
    $form['order_no']   = (string)max(1, (int)($_POST['order_no'] ?? 1));
    $form['dob']        = trim((string)($_POST['dob'] ?? ''));
    $form['vatno']      = trim((string)($_POST['vatno'] ?? ''));
    $form['tinno']      = trim((string)($_POST['tinno'] ?? ''));
    $form['phone']      = trim((string)($_POST['phone'] ?? ''));
    $form['contact']    = trim((string)($_POST['contact'] ?? ''));
    $form['payment_type'] = trim((string)($_POST['payment_type'] ?? 'on_account'));
    if (!in_array($form['payment_type'], ['prepayment', 'on_account'], true)) {
        $form['payment_type'] = 'on_account';
    }

    $form['rate_plan_id'] = trim((string)($_POST['rate_plan_id'] ?? ''));
    $form['group_rate_plan_id'] = trim((string)($_POST['group_rate_plan_id'] ?? ''));
    $form['rate_contract_id'] = trim((string)($_POST['rate_contract_id'] ?? ''));
    $form['group_rate_contract_id'] = trim((string)($_POST['group_rate_contract_id'] ?? ''));

    /* The picker submits a CONTRACT. Derive the matching rate_plan_id from it
       and keep both columns in step, so the legacy fallback in
       fetch_rate_plan() still resolves for this agent. BB is preferred as the
       representative plan purely because it is the near-universal base here;
       the meal plan that actually prices a night is the one on the booking,
       resolved against the contract, not this value. */
    if ($hasRateContracts) {
        $form['rate_plan_id'] = agents_plan_id_for_contract($pdo, $form['rate_contract_id']);
        $form['group_rate_plan_id'] = agents_plan_id_for_contract($pdo, $form['group_rate_contract_id']);
    }

    $editing = $form['id'] > 0;

    if ($form['firstname'] === '') {
        $errors[] = 'First name is required.';
    }
    if ($form['email'] !== '' && !filter_var($form['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }    if (!$editing && $form['password'] === '') {
       // $errors[] = 'Password is required for a new agent.';
    }

    if ($hasRateContracts && $form['rate_contract_id'] !== '') {
        try {
            $rcCheck = $pdo->prepare("SELECT id FROM rate_contracts WHERE id = :id LIMIT 1");
            $rcCheck->execute([':id' => (int)$form['rate_contract_id']]);
            if (!$rcCheck->fetchColumn()) {
                $errors[] = 'The selected rate contract was not found.';
            }
        } catch (Throwable $e) {
            $errors[] = 'Could not validate the selected rate contract: ' . $e->getMessage();
        }
    }

    if ($hasAgentGroupContractLink && $form['group_rate_contract_id'] !== '') {
        try {
            $grcCheck = $pdo->prepare("SELECT id FROM rate_contracts WHERE id = :id LIMIT 1");
            $grcCheck->execute([':id' => (int)$form['group_rate_contract_id']]);
            if (!$grcCheck->fetchColumn()) {
                $errors[] = 'The selected group rate contract was not found.';
            }
        } catch (Throwable $e) {
            $errors[] = 'Could not validate the selected group rate contract: ' . $e->getMessage();
        }
    }

    if (!$hasRateContracts && $form['rate_plan_id'] !== '') {
        if (!agents_table_exists($pdo, 'rate_plans')
            || !agents_column_exists($pdo, 'agents', 'rate_plan_id')) {
            $errors[] = 'Rate contract linkage is not available in this database.';
        } else {
            try {
                $rateCheck = $pdo->prepare("SELECT id FROM rate_plans WHERE id = :id LIMIT 1");
                $rateCheck->execute([':id' => (int)$form['rate_plan_id']]);
                if (!$rateCheck->fetchColumn()) {
                    $errors[] = 'The selected rate contract was not found.';
                }
            } catch (Throwable $e) {
                $errors[] = 'Could not validate the selected rate contract: ' . $e->getMessage();
            }
        }
    }

    if (!$hasRateContracts && $form['group_rate_plan_id'] !== '') {
        if (!agents_table_exists($pdo, 'rate_plans')
            || !agents_column_exists_fresh($pdo, 'agents', 'group_rate_plan_id')) {
            $errors[] = 'Group rate contract linkage is not available in this database.';
        } else {
            try {
                $groupCheck = $pdo->prepare("SELECT id FROM rate_plans WHERE id = :id LIMIT 1");
                $groupCheck->execute([':id' => (int)$form['group_rate_plan_id']]);
                if (!$groupCheck->fetchColumn()) {
                    $errors[] = 'The selected group rate contract was not found.';
                }
            } catch (Throwable $e) {
                $errors[] = 'Could not validate the selected group rate contract: ' . $e->getMessage();
            }
        }
    }

    /* Only enforce email uniqueness when an email was actually entered.
       Blank emails are allowed for multiple agents. */
    if ($form['email'] !== '') {
        try {
            $stmt = $pdo->prepare("
                SELECT id
                FROM agents
                WHERE LOWER(TRIM(email)) = LOWER(TRIM(:email))
                  AND id <> :id
                LIMIT 1
            ");
            $stmt->execute([
                ':email' => $form['email'],
                ':id'    => (int)$form['id'],
            ]);
            if ($stmt->fetch(PDO::FETCH_ASSOC)) {
                $errors[] = 'An agent with that email already exists.';
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!$errors) {
        try {
            if ($editing) {
                if ($form['password'] !== '') {
                    $stmt = $pdo->prepare("
                        UPDATE agents
                        SET firstname = :firstname,
                            lastname = :lastname,
                            gender = :gender,
                            office = :office,
                            email = :email,
                            password = :password,
                            country_id = :country_id,
                            state_id = :state_id,
                            city_id = :city_id,
                            address = :address,
                            mobile = :mobile,
                            id_type = :id_type,
                            id_no = :id_no,
                            id_upload = :id_upload,
                            remark = :remark,
                            vip = :vip,
                            order_no = :order_no,
                            dob = :dob,
                            vatno = :vatno,
                            tinno = :tinno,
                            phone = :phone,
                            contact = :contact,
                            payment_type = :payment_type,
                            rate_plan_id = :rate_plan_id
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':firstname'  => $form['firstname'],
                        ':lastname'   => $form['lastname'],
                        ':gender'     => (int)$form['gender'],
                        ':office'     => $form['office'],
                        ':email'      => $form['email'],
                        ':password'   => hash_agent_password($form['password']),
                        ':country_id' => (int)$form['country_id'],
                        ':state_id'   => (int)$form['state_id'],
                        ':city_id'    => (int)$form['city_id'],
                        ':address'    => $form['address'],
                        ':mobile'     => $form['mobile'],
                        ':id_type'    => $form['id_type'] !== '' ? $form['id_type'] : null,
                        ':id_no'      => $form['id_no'] !== '' ? $form['id_no'] : null,
                        ':id_upload'  => $form['id_upload'] !== '' ? $form['id_upload'] : null,
                        ':remark'     => $form['remark'] !== '' ? $form['remark'] : null,
                        ':vip'        => (int)$form['vip'],
                        ':order_no'   => (int)$form['order_no'],
                        ':dob'        => $form['dob'] !== '' ? $form['dob'] : null,
                        ':vatno'      => $form['vatno'] !== '' ? $form['vatno'] : null,
                        ':tinno'      => $form['tinno'] !== '' ? $form['tinno'] : null,
                        ':phone'      => $form['phone'] !== '' ? $form['phone'] : null,
                        ':contact'    => $form['contact'] !== '' ? $form['contact'] : null,
                        ':payment_type' => $form['payment_type'],
                        ':rate_plan_id' => $form['rate_plan_id'] !== '' ? (int)$form['rate_plan_id'] : null,
                        ':id'         => (int)$form['id'],
                    ]);
                } else {
                    $stmt = $pdo->prepare("
                        UPDATE agents
                        SET firstname = :firstname,
                            lastname = :lastname,
                            gender = :gender,
                            office = :office,
                            email = :email,
                            country_id = :country_id,
                            state_id = :state_id,
                            city_id = :city_id,
                            address = :address,
                            mobile = :mobile,
                            id_type = :id_type,
                            id_no = :id_no,
                            id_upload = :id_upload,
                            remark = :remark,
                            vip = :vip,
                            order_no = :order_no,
                            dob = :dob,
                            vatno = :vatno,
                            tinno = :tinno,
                            phone = :phone,
                            contact = :contact,
                            payment_type = :payment_type,
                            rate_plan_id = :rate_plan_id
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':firstname'  => $form['firstname'],
                        ':lastname'   => $form['lastname'],
                        ':gender'     => (int)$form['gender'],
                        ':office'     => $form['office'],
                        ':email'      => $form['email'],
                        ':country_id' => (int)$form['country_id'],
                        ':state_id'   => (int)$form['state_id'],
                        ':city_id'    => (int)$form['city_id'],
                        ':address'    => $form['address'],
                        ':mobile'     => $form['mobile'],
                        ':id_type'    => $form['id_type'] !== '' ? $form['id_type'] : null,
                        ':id_no'      => $form['id_no'] !== '' ? $form['id_no'] : null,
                        ':id_upload'  => $form['id_upload'] !== '' ? $form['id_upload'] : null,
                        ':remark'     => $form['remark'] !== '' ? $form['remark'] : null,
                        ':vip'        => (int)$form['vip'],
                        ':order_no'   => (int)$form['order_no'],
                        ':dob'        => $form['dob'] !== '' ? $form['dob'] : null,
                        ':vatno'      => $form['vatno'] !== '' ? $form['vatno'] : null,
                        ':tinno'      => $form['tinno'] !== '' ? $form['tinno'] : null,
                        ':phone'      => $form['phone'] !== '' ? $form['phone'] : null,
                        ':contact'    => $form['contact'] !== '' ? $form['contact'] : null,
                        ':payment_type' => $form['payment_type'],
                        ':rate_plan_id' => $form['rate_plan_id'] !== '' ? (int)$form['rate_plan_id'] : null,
                        ':id'         => (int)$form['id'],
                    ]);
                }
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO agents
                    (
                        firstname, lastname, gender, office, email, password,
                        country_id, state_id, city_id, address, mobile,
                        id_type, id_no, id_upload, remark, added, vip, token,
                        order_no, dob, vatno, tinno, phone, contact, payment_type, rate_plan_id
                    )
                    VALUES
                    (
                        :firstname, :lastname, :gender, :office, :email, :password,
                        :country_id, :state_id, :city_id, :address, :mobile,
                        :id_type, :id_no, :id_upload, :remark, NOW(), :vip, NULL,
                        :order_no, :dob, :vatno, :tinno, :phone, :contact, :payment_type, :rate_plan_id
                    )
                ");
                $stmt->execute([
                    ':firstname'  => $form['firstname'],
                    ':lastname'   => $form['lastname'],
                    ':gender'     => (int)$form['gender'],
                    ':office'     => $form['office'],
                    ':email'      => $form['email'],
                    ':password'   => hash_agent_password($form['password']),
                    ':country_id' => (int)$form['country_id'],
                    ':state_id'   => (int)$form['state_id'],
                    ':city_id'    => (int)$form['city_id'],
                    ':address'    => $form['address'],
                    ':mobile'     => $form['mobile'],
                    ':id_type'    => $form['id_type'] !== '' ? $form['id_type'] : null,
                    ':id_no'      => $form['id_no'] !== '' ? $form['id_no'] : null,
                    ':id_upload'  => $form['id_upload'] !== '' ? $form['id_upload'] : null,
                    ':remark'     => $form['remark'] !== '' ? $form['remark'] : null,
                    ':vip'        => (int)$form['vip'],
                    ':order_no'   => (int)$form['order_no'],
                    ':dob'        => $form['dob'] !== '' ? $form['dob'] : null,
                    ':vatno'      => $form['vatno'] !== '' ? $form['vatno'] : null,
                    ':tinno'      => $form['tinno'] !== '' ? $form['tinno'] : null,
                    ':phone'      => $form['phone'] !== '' ? $form['phone'] : null,
                    ':contact'    => $form['contact'] !== '' ? $form['contact'] : null,
                    ':payment_type' => $form['payment_type'],
                    ':rate_plan_id' => $form['rate_plan_id'] !== '' ? (int)$form['rate_plan_id'] : null,
                ]);
                $form['id'] = (int)$pdo->lastInsertId();
            }

            /*
               Persist the GROUP rate contract separately. Kept out of the main
               INSERT/UPDATE statements so the page still works unchanged on
               installs where agents.group_rate_plan_id does not exist (and
               could not be created).
            */
            if (agents_column_exists_fresh($pdo, 'agents', 'group_rate_plan_id') && (int)$form['id'] > 0) {
                try {
                    $pdo->prepare("UPDATE agents SET group_rate_plan_id = :gid WHERE id = :id")
                        ->execute([
                            ':gid' => $form['group_rate_plan_id'] !== '' ? (int)$form['group_rate_plan_id'] : null,
                            ':id'  => (int)$form['id'],
                        ]);
                } catch (Throwable $e) {
                    // Non-fatal: the agent itself saved fine.
                }
            }

            /*
               Persist the CONTRACT link. This is the column fetch_rate_plan()
               resolves against, so an agent saved from this page keeps working
               for every meal plan its contract holds. Kept separate from the
               main INSERT/UPDATE for the same reason as the group column: the
               page must still save on an install without rate_contracts.
            */
            if ($hasRateContracts && (int)$form['id'] > 0) {
                try {
                    $pdo->prepare("UPDATE agents SET rate_contract_id = :cid WHERE id = :id")
                        ->execute([
                            ':cid' => $form['rate_contract_id'] !== '' ? (int)$form['rate_contract_id'] : null,
                            ':id'  => (int)$form['id'],
                        ]);
                } catch (Throwable $e) {
                    throw new RuntimeException('Could not save the rate contract: ' . $e->getMessage());
                }
            }

            if ($hasAgentGroupContractLink && (int)$form['id'] > 0) {
                try {
                    $pdo->prepare("UPDATE agents SET group_rate_contract_id = :gcid WHERE id = :id")
                        ->execute([
                            ':gcid' => $form['group_rate_contract_id'] !== '' ? (int)$form['group_rate_contract_id'] : null,
                            ':id'   => (int)$form['id'],
                        ]);
                } catch (Throwable $e) {
                    throw new RuntimeException('Could not save the group rate contract: ' . $e->getMessage());
                }
            }

            header('Location: agents.php?saved=1');
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'agent') {
    header('Content-Type: application/json; charset=utf-8');
    $agentId = (int)($_GET['id'] ?? 0);
    try {
        $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $agentId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            echo json_encode(['ok' => false, 'message' => 'Agent not found.']);
            exit;
        }
        if (empty($row['rate_contract_id']) && !empty($row['rate_plan_id']) && $hasRateContracts) {
            $row['rate_contract_id'] = agents_contract_id_for_plan($pdo, $row['rate_plan_id']);
        }
        if (empty($row['group_rate_contract_id']) && !empty($row['group_rate_plan_id']) && $hasAgentGroupContractLink) {
            $row['group_rate_contract_id'] = agents_contract_id_for_plan($pdo, $row['group_rate_plan_id']);
        }
        echo json_encode(['ok' => true, 'row' => $row]);
    } catch (Throwable $e) {
        echo json_encode(['ok' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
    $deleteId = (int)$_GET['delete'];

    try {
        /*
         * Only agents with no bookings may be deleted.
         * Check every supported agent reference in orders so an agent used as
         * either the main agent or originating agent remains protected.
         */
        if (!agents_table_exists($pdo, 'orders')) {
            throw new RuntimeException('The orders table is unavailable, so deletion was blocked for safety.');
        }

        $orderAgentColumns = [];
        foreach (['agent_id', 'originating_agent'] as $agentColumn) {
            if (agents_column_exists($pdo, 'orders', $agentColumn)) {
                $orderAgentColumns[] = "`{$agentColumn}` = :agent_id";
            }
        }

        if (!$orderAgentColumns) {
            throw new RuntimeException('No agent-reference column was found in the orders table, so deletion was blocked for safety.');
        }

        $bookingStmt = $pdo->prepare(
            "SELECT COUNT(*) FROM orders WHERE (" . implode(' OR ', $orderAgentColumns) . ")"
        );
        $bookingStmt->execute([':agent_id' => $deleteId]);
        $bookingCount = (int)$bookingStmt->fetchColumn();

        if ($bookingCount > 0) {
            header('Location: agents.php?' . http_build_query([
                'delete_blocked' => 1,
                'booking_count'  => $bookingCount,
            ]));
            exit;
        }

        $stmt = $pdo->prepare("DELETE FROM agents WHERE id = :id");
        $stmt->execute([':id' => $deleteId]);

        if ($stmt->rowCount() < 1) {
            throw new RuntimeException('Agent not found or already deleted.');
        }

        header('Location: agents.php?deleted=1');
        exit;
    } catch (Throwable $e) {
        header('Location: agents.php?delete_error=1');
        exit;
    }
}

if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $editId = (int)$_GET['edit'];

    try {
        $stmt = $pdo->prepare("SELECT * FROM agents WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $editing = true;

            /* Resolve the rate contract this agent is on, if any, for display in
               the form. Guarded so it is a no-op where the schema lacks it. */
            $editRatePlanId    = null;
            $editRatePlanTitle = '';
            $editRatePlanCode  = '';
            if (agents_table_exists($pdo, 'rate_plans')
                && agents_column_exists($pdo, 'agents', 'rate_plan_id')
                && !empty($row['rate_plan_id'])) {
                $rpTitleColEdit = null;
                foreach (['title', 'name', 'plan_name', 'rate_name'] as $rpC) {
                    if (agents_column_exists($pdo, 'rate_plans', $rpC)) { $rpTitleColEdit = $rpC; break; }
                }
                $rpTitleExprEdit = $rpTitleColEdit ? "`{$rpTitleColEdit}`" : "CONCAT('Rate #', id)";
                $rpCodeExprEdit  = agents_column_exists($pdo, 'rate_plans', 'code') ? "code" : "NULL";
                try {
                    $rpStmt = $pdo->prepare("SELECT id, {$rpTitleExprEdit} AS title, {$rpCodeExprEdit} AS code FROM rate_plans WHERE id = :id LIMIT 1");
                    $rpStmt->execute([':id' => (int)$row['rate_plan_id']]);
                    if ($rpRow = $rpStmt->fetch(PDO::FETCH_ASSOC)) {
                        $editRatePlanId    = (int)$rpRow['id'];
                        $editRatePlanTitle = (string)$rpRow['title'];
                        $editRatePlanCode  = (string)($rpRow['code'] ?? '');
                    }
                } catch (Throwable $e) { /* non-fatal: just skip the display */ }
            }

            $form = [
                'id'         => (int)$row['id'],
                'firstname'  => (string)$row['firstname'],
                'lastname'   => (string)$row['lastname'],
                'gender'     => (string)(int)$row['gender'],
                'office'     => (string)$row['office'],
                'email'      => (string)$row['email'],
                'password'   => '',
                'country_id' => (string)$row['country_id'],
                'state_id'   => (string)$row['state_id'],
                'city_id'    => (string)$row['city_id'],
                'address'    => (string)$row['address'],
                'mobile'     => (string)$row['mobile'],
                'id_type'    => (string)($row['id_type'] ?? ''),
                'id_no'      => (string)($row['id_no'] ?? ''),
                'id_upload'  => (string)($row['id_upload'] ?? ''),
                'remark'     => (string)($row['remark'] ?? ''),
                'vip'        => (string)(int)$row['vip'],
                'order_no'   => (string)(int)($row['order_no'] ?? 1),
                'dob'        => !empty($row['dob']) ? date('Y-m-d', strtotime((string)$row['dob'])) : '',
                'vatno'      => (string)($row['vatno'] ?? ''),
                'tinno'      => (string)($row['tinno'] ?? ''),
                'phone'      => (string)($row['phone'] ?? ''),
                'contact'    => (string)($row['contact'] ?? ''),
                'payment_type' => (string)($row['payment_type'] ?? 'on_account'),
                'rate_plan_id' => !empty($row['rate_plan_id']) ? (string)(int)$row['rate_plan_id'] : '',
                'group_rate_plan_id' => !empty($row['group_rate_plan_id']) ? (string)(int)$row['group_rate_plan_id'] : '',
                /* Fall back to deriving the contract from the legacy plan link,
                   so an agent migrated before rate_contract_id was populated
                   still shows its contract correctly on the edit form. */
                'rate_contract_id' => !empty($row['rate_contract_id'])
                    ? (string)(int)$row['rate_contract_id']
                    : ($hasRateContracts && !empty($row['rate_plan_id'])
                        ? agents_contract_id_for_plan($pdo, $row['rate_plan_id'])
                        : ''),
                'group_rate_contract_id' => !empty($row['group_rate_contract_id'])
                    ? (string)(int)$row['group_rate_contract_id']
                    : ($hasAgentGroupContractLink && !empty($row['group_rate_plan_id'])
                        ? agents_contract_id_for_plan($pdo, $row['group_rate_plan_id'])
                        : ''),
            ];
        } else {
            $errors[] = 'Agent not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'states') {
    header('Content-Type: application/json; charset=utf-8');
    $countryId = (int)($_GET['country_id'] ?? 0);
    echo json_encode([
        'ok' => true,
        'rows' => fetch_states_by_country($pdo, $countryId),
    ]);
    exit;
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'cities') {
    header('Content-Type: application/json; charset=utf-8');
    $stateId = (int)($_GET['state_id'] ?? 0);
    echo json_encode([
        'ok' => true,
        'rows' => fetch_cities_by_state($pdo, $stateId),
    ]);
    exit;
}

$countries = fetch_countries($pdo);
$states = fetch_states_by_country($pdo, (int)$form['country_id']);
$cities = fetch_cities_by_state($pdo, (int)$form['state_id']);

$countryMap = [];
foreach ($countries as $r) {
    $countryMap[(string)$r['id']] = $r['name'];
}
$stateMap = [];
foreach ($states as $r) {
    $stateMap[(string)$r['id']] = $r['name'];
}

$search = trim((string)($_GET['q'] ?? ''));

$hasCountries = agents_table_exists($pdo, 'countries');
$hasStates    = agents_table_exists($pdo, 'states');
$hasCities    = agents_table_exists($pdo, 'cities');

/* Rate contract linkage.
   An agent is linked to a CONTRACT, not to a plan. A contract groups the
   per-meal-plan rate_plans rows (BAOBAB -> BAOBAB BB + BAOBAB HB), and the
   meal plan is chosen on the BOOKING, then resolved at pricing time by
   fetch_rate_plan() in includes/rate_support.php.

   The old link was agents.rate_plan_id -> rate_plans.id, a scalar. Since every
   rate_plans row carries exactly one meal_plan, that pinned each agent to ONE
   meal plan: an agent on 'BAOBAB BB' asking for HB matched nothing and fell
   through to the rack rate, silently and at the wrong price.

   rate_plan_id is still written on save, kept in step with the contract, so
   the legacy fallback path in fetch_rate_plan() stays correct for anything not
   yet migrated. Everything is guarded: on an install without rate_contracts
   this page behaves exactly as it did before. */
/* Schema capabilities were resolved before POST/AJAX handling. */
$ratePlanTitleCol = null;
if ($hasRatePlans) {
    foreach (['title', 'name', 'plan_name', 'rate_name'] as $rpCol) {
        if (agents_column_exists($pdo, 'rate_plans', $rpCol)) { $ratePlanTitleCol = $rpCol; break; }
    }
}
$hasRatePlanCode = $hasRatePlans && agents_column_exists($pdo, 'rate_plans', 'code');

/* Contract options. Each row also carries the meal plans it actually holds,
   so the picker can show 'BAOBAB - BB, HB' and make a BB-only contract
   visible at the point of assignment rather than at folio time. */
$rateContracts = [];
if ($hasRateContracts) {
    try {
        $rcTitleCol = null;
        foreach (['title', 'name'] as $rcCol) {
            if (agents_column_exists($pdo, 'rate_contracts', $rcCol)) { $rcTitleCol = $rcCol; break; }
        }
        $rcTitleExpr = $rcTitleCol ? "rc.`{$rcTitleCol}`" : "rc.code";
        $rcStatus = agents_column_exists($pdo, 'rate_contracts', 'status')
            ? " WHERE rc.status = 1 " : " ";
        $rcStmt = $pdo->query("
            SELECT
                rc.id,
                rc.code,
                {$rcTitleExpr} AS title,
                GROUP_CONCAT(DISTINCT rp.meal_plan ORDER BY rp.meal_plan SEPARATOR ', ') AS meal_plans
            FROM rate_contracts rc
            LEFT JOIN rate_plans rp
                ON rp.contract_id = rc.id AND rp.status = 1
            {$rcStatus}
            GROUP BY rc.id, rc.code, {$rcTitleExpr}
            ORDER BY rc.code ASC
        ");
        $rateContracts = $rcStmt ? $rcStmt->fetchAll(PDO::FETCH_ASSOC) : [];
    } catch (Throwable $e) {
        $rateContracts = [];
        $errors[] = 'Could not load rate contracts: ' . $e->getMessage();
    }
}

$ratePlans = [];
if ($hasAgentRateLink || $hasAgentGroupRateLink) {
    try {
        $ratePlanTitleExpr = $ratePlanTitleCol
            ? "`{$ratePlanTitleCol}`"
            : "CONCAT('Rate #', id)";
        $ratePlanCodeExpr = $hasRatePlanCode ? "code" : "NULL";
        $ratePlanOrder = $ratePlanTitleCol
            ? "`{$ratePlanTitleCol}` ASC, id ASC"
            : "id ASC";

        $ratePlanStmt = $pdo->query("
            SELECT
                id,
                {$ratePlanTitleExpr} AS title,
                {$ratePlanCodeExpr} AS code
            FROM rate_plans
            ORDER BY {$ratePlanOrder}
        ");
        $ratePlans = $ratePlanStmt ? $ratePlanStmt->fetchAll(PDO::FETCH_ASSOC) : [];
    } catch (Throwable $e) {
        $ratePlans = [];
        $errors[] = 'Could not load rate contracts: ' . $e->getMessage();
    }
}

$selectCountry = $hasCountries ? "c.name AS country_name" : "'' AS country_name";
$selectState   = $hasStates ? "s.name AS state_name" : "'' AS state_name";
$selectCity    = $hasCities ? "ci.name AS city_name" : "'' AS city_name";

// Rate plan name/code/id to display in the list. NULL-safe: unassigned agents
// simply return NULLs here.
if ($hasRateContracts) {
    /* Show the CONTRACT, with the meal plans it holds. Falls back to the
       legacy plan title for agents whose rate_contract_id is not yet set. */
    $rpTitleExpr = $ratePlanTitleCol ? "rp.`{$ratePlanTitleCol}`" : "CONCAT('Rate #', rp.id)";
    $rpCodeExpr  = $hasRatePlanCode ? "rp.code" : "NULL";
    $selectRatePlan = "
        a.rate_plan_id AS rate_plan_id,
        a.rate_contract_id AS rate_contract_id,
        COALESCE(arc.code, {$rpTitleExpr}) AS rate_plan_title,
        {$rpCodeExpr} AS rate_plan_code,
        (SELECT GROUP_CONCAT(DISTINCT arp.meal_plan ORDER BY arp.meal_plan SEPARATOR ', ')
           FROM rate_plans arp
          WHERE arp.contract_id = a.rate_contract_id AND arp.status = 1) AS rate_contract_meals";
} elseif ($hasAgentRateLink) {
    $rpTitleExpr = $ratePlanTitleCol ? "rp.`{$ratePlanTitleCol}`" : "CONCAT('Rate #', rp.id)";
    $rpCodeExpr  = $hasRatePlanCode ? "rp.code" : "NULL";
    $selectRatePlan = "a.rate_plan_id AS rate_plan_id, NULL AS rate_contract_id, {$rpTitleExpr} AS rate_plan_title, {$rpCodeExpr} AS rate_plan_code, NULL AS rate_contract_meals";
} else {
    $selectRatePlan = "NULL AS rate_plan_id, NULL AS rate_contract_id, NULL AS rate_plan_title, NULL AS rate_plan_code, NULL AS rate_contract_meals";
}

if ($hasAgentGroupRateLink) {
    $grpTitleExpr = $ratePlanTitleCol ? "grp.`{$ratePlanTitleCol}`" : "CONCAT('Rate #', grp.id)";
    $grpCodeExpr  = $hasRatePlanCode ? "grp.code" : "NULL";
    $selectGroupRatePlan = "a.group_rate_plan_id AS group_rate_plan_id, {$grpTitleExpr} AS group_rate_plan_title, {$grpCodeExpr} AS group_rate_plan_code";
} else {
    $selectGroupRatePlan = "NULL AS group_rate_plan_id, NULL AS group_rate_plan_title, NULL AS group_rate_plan_code";
}

$sql = "
    SELECT
        a.*,
        {$selectCountry},
        {$selectState},
        {$selectCity},
        {$selectRatePlan},
        {$selectGroupRatePlan}
    FROM agents a
";

if ($hasAgentRateLink) {
    $sql .= " LEFT JOIN rate_plans rp ON rp.id = a.rate_plan_id ";
}

if ($hasRateContracts) {
    $sql .= " LEFT JOIN rate_contracts arc ON arc.id = a.rate_contract_id ";
}

if ($hasAgentGroupRateLink) {
    $sql .= " LEFT JOIN rate_plans grp ON grp.id = a.group_rate_plan_id ";
}

if ($hasCountries) {
    $sql .= " LEFT JOIN countries c ON c.id = a.country_id ";
}
if ($hasStates) {
    $sql .= " LEFT JOIN states s ON s.id = a.state_id ";
}
if ($hasCities) {
    $sql .= " LEFT JOIN cities ci ON ci.id = a.city_id ";
}

$sql .= " WHERE 1=1 ";
$params = [];

if ($search !== '') {
    $searchParts = [];
    $searchValue = '%' . $search . '%';
    $searchIndex = 0;

    $addSearchPart = function (string $expression) use (&$searchParts, &$params, &$searchIndex, $searchValue): void {
        $placeholder = ':search_' . $searchIndex++;
        $searchParts[] = $expression . ' LIKE ' . $placeholder;
        $params[$placeholder] = $searchValue;
    };

    foreach (['firstname', 'lastname', 'email', 'office', 'mobile', 'phone', 'contact', 'address', 'vatno', 'tinno'] as $col) {
        if (agents_column_exists($pdo, 'agents', $col)) {
            $addSearchPart("a.`{$col}`");
        }
    }

    if ($hasCountries && agents_column_exists($pdo, 'countries', 'name')) {
        $addSearchPart('c.name');
    }
    if ($hasStates && agents_column_exists($pdo, 'states', 'name')) {
        $addSearchPart('s.name');
    }
    if ($hasCities && agents_column_exists($pdo, 'cities', 'name')) {
        $addSearchPart('ci.name');
    }

    if ($searchParts) {
        $sql .= " AND (" . implode(" OR ", $searchParts) . ") ";
    }
}
$sql .= " ORDER BY a.id DESC LIMIT 500";

$agents = [];
try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $agents = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not search agents: ' . $e->getMessage();
}
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band agents-compact-hero">
    <div class="row g-2 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-people"></i> Masters</div>
            <div class="hero-title mt-1">Agents</div>
            <div class="hero-subtitle mt-1">
                Manage agent profiles, contact details, tax references, and cascading location selection.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <button type="button" class="btn btn-outline-light btn-sm" id="openNewAgentBtn">
                <i class="bi bi-plus-circle me-2"></i>New Agent
            </button>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo h($success); ?></div>
<?php endif; ?>

<!-- Full-width agent listing. The add/edit form now lives in the modal below. -->
<div class="agents-page">

    <!-- ============================================================
         ADD / EDIT AGENT MODAL
         The same server-rendered form as before, just relocated into a
         modal. It auto-opens when adding failed validation or when an
         agent is being edited (?edit=ID), so the server keeps filling
         $form exactly as it always did.
         ============================================================ -->
    <div class="modal fade" id="agentModal" tabindex="-1" aria-labelledby="agentModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-xl modal-dialog-scrollable modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="agentModalLabel">
                <i class="bi bi-person-vcard me-2"></i>
                <span id="agentModalTitleText"><?php echo $editing ? 'Edit Agent' : 'New Agent'; ?></span>
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>

            <form method="post" class="row g-3 modal-body" id="agentForm">
                <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

                <?php if ($errors): ?>
                    <div class="col-12">
                        <div class="alert alert-danger mb-0">
                            <div class="fw-bold mb-2">Please fix the following:</div>
                            <ul class="mb-0">
                                <?php foreach ($errors as $err): ?>
                                    <li><?php echo h($err); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="col-md-6">
                    <label class="form-label">Agent Name</label>
                    <input type="text" name="firstname" class="form-control" value="<?php echo h($form['firstname']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Registered Name <span class="text-muted small">(defaults to Agent Name)</span></label>
                    <input type="text" name="lastname" class="form-control" value="<?php echo h($form['lastname']); ?>">
                </div>

                <div class="col-md-6" style="display:none">
                    <label class="form-label">Gender</label>
                    <select name="gender" class="form-select">
                        <option value="0" <?php echo $form['gender'] === '0' ? 'selected' : ''; ?>>Not Set</option>
                        <option value="1" <?php echo $form['gender'] === '1' ? 'selected' : ''; ?>>Male</option>
                        <option value="2" <?php echo $form['gender'] === '2' ? 'selected' : ''; ?>>Female</option>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">WhatsApp</label>
                    <input type="text" name="office" class="form-control" value="<?php echo h($form['office']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" value="<?php echo h($form['email']); ?>">
                </div>

                <div class="col-md-6"  style="display:none">
                    <label class="form-label"><?php echo $editing ? 'New Password (optional)' : 'Password'; ?></label>
                    <input type="password" name="password" class="form-control" >
                </div>

                <div class="col-md-6">
                    <label class="form-label">Mobile</label>
                    <input type="text" name="mobile" class="form-control" value="<?php echo h($form['mobile']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Phone</label>
                    <input type="text" name="phone" class="form-control" value="<?php echo h($form['phone']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Contact</label>
                    <input type="text" name="contact" class="form-control" value="<?php echo h($form['contact']); ?>">
                </div>

                <div class="col-md-6"  style="display:none">
                    <label class="form-label">Order No</label>
                    <input type="number" min="1" value="1" name="order_no" class="form-control" value="<?php echo h($form['order_no']); ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Address</label>
                    <textarea name="address" class="form-control" rows="3"><?php echo h($form['address']); ?></textarea>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Country</label>
                    <select name="country_id" id="country_id" class="form-select">
                        <option value="">Select country</option>
                        <?php foreach ($countries as $opt): ?>
                            <option value="<?php echo (int)$opt['id']; ?>" <?php echo (int)$form['country_id'] === (int)$opt['id'] ? 'selected' : ''; ?>>
                                <?php echo h($opt['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-4">
                    <label class="form-label">State</label>
                    <select name="state_id" id="state_id" class="form-select">
                        <option value="">Select state</option>
                        <?php foreach ($states as $opt): ?>
                            <option value="<?php echo (int)$opt['id']; ?>" <?php echo (int)$form['state_id'] === (int)$opt['id'] ? 'selected' : ''; ?>>
                                <?php echo h($opt['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-4">
                    <label class="form-label">City</label>
                    <select name="city_id" id="city_id" class="form-select">
                        <option value="">Select city</option>
                        <?php foreach ($cities as $opt): ?>
                            <option value="<?php echo (int)$opt['id']; ?>" <?php echo (int)$form['city_id'] === (int)$opt['id'] ? 'selected' : ''; ?>>
                                <?php echo h($opt['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>



                <div class="col-md-4"  style="display:none" >
                    <label class="form-label">ID Type</label>
                    <input type="text" name="id_type" class="form-control" value="<?php echo h($form['id_type']); ?>">
                </div>

                <div class="col-md-4"  style="display:none">
                    <label class="form-label">ID No</label>
                    <input type="text" name="id_no" class="form-control" value="<?php echo h($form['id_no']); ?>">
                </div>

                <div class="col-md-4"  style="display:none">
                    <label class="form-label">ID Upload</label>
                    <input type="text" name="id_upload" class="form-control" value="<?php echo h($form['id_upload']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">VAT No</label>
                    <input type="text" name="vatno" class="form-control" value="<?php echo h($form['vatno']); ?>">
                </div>

                <div class="col-md-6">
                    <label class="form-label">TIN No</label>
                    <input type="text" name="tinno" class="form-control" value="<?php echo h($form['tinno']); ?>">
                </div>

                <div class="col-md-4"  style="display:none">
                    <label class="form-label">DOB</label>
                    <input type="date" name="dob" class="form-control" value="<?php echo h($form['dob']); ?>">
                </div>

                <div class="col-md-6" style="display:none">
                    <label class="form-label">VIP Agent</label>
                    <select name="vip" class="form-select">
                        <option value="0" <?php echo $form['vip'] === '0' ? 'selected' : ''; ?>>No</option>
                        <option value="1" <?php echo $form['vip'] === '1' ? 'selected' : ''; ?>>Yes</option>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Payment Type</label>
                    <select name="payment_type" class="form-select">
                        <option value="on_account" <?php echo $form['payment_type'] === 'on_account' ? 'selected' : ''; ?>>On Account</option>
                        <option value="prepayment" <?php echo $form['payment_type'] === 'prepayment' ? 'selected' : ''; ?>>Prepayment</option>
                    </select>
                </div>

                <div class="col-md-6" id="agentRatePlanBlock">
                    <label class="form-label">Rate Contract</label>

                    <?php if ($hasRateContracts): ?>
                        <select name="rate_contract_id" class="form-select">
                            <option value="">Public / Rack Rate</option>

                            <?php foreach ($rateContracts as $rateContract): ?>
                                <?php
                                $rcId    = (int)$rateContract['id'];
                                $rcTitle = trim((string)($rateContract['title'] ?? ''));
                                $rcCode  = trim((string)($rateContract['code'] ?? ''));
                                $rcMeals = trim((string)($rateContract['meal_plans'] ?? ''));

                                $rcLabel = $rcTitle !== '' ? $rcTitle : ('Contract #' . $rcId);
                                if ($rcCode !== '' && $rcCode !== $rcTitle) {
                                    $rcLabel .= ' (' . $rcCode . ')';
                                }
                                // Show which meal plans the contract actually holds, so a
                                // BB-only contract is obvious here rather than at folio time.
                                $rcLabel .= ' - ' . ($rcMeals !== '' ? $rcMeals : 'no rates');
                                ?>
                                <option
                                    value="<?php echo $rcId; ?>"
                                    <?php echo (int)($form['rate_contract_id'] ?: 0) === $rcId ? 'selected' : ''; ?>>
                                    <?php echo h($rcLabel); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="form-text">
                            The agent's contract. The <strong>meal plan is chosen on the
                            booking</strong>, not here &mdash; a contract holding BB and HB
                            prices either. A contract shown as <strong>BB</strong> only has
                            no HB rate: those bookings fall back to a meal supplement, or to
                            the rack rate, and are flagged on the reservation.
                            <a href="rate_contracts.php" target="_blank">Manage contracts</a>
                        </div>
                    <?php elseif ($hasAgentRateLink): ?>
                        <select name="rate_plan_id" class="form-select">
                            <option value="">Public / Rack Rate</option>

                            <?php foreach ($ratePlans as $ratePlan): ?>
                                <?php
                                $ratePlanId = (int)$ratePlan['id'];
                                $ratePlanTitle = trim((string)($ratePlan['title'] ?? ''));
                                $ratePlanCode = trim((string)($ratePlan['code'] ?? ''));
                                $ratePlanLabel = $ratePlanTitle !== ''
                                    ? $ratePlanTitle
                                    : ('Rate #' . $ratePlanId);

                                if ($ratePlanCode !== '') {
                                    $ratePlanLabel .= ' (' . $ratePlanCode . ')';
                                }
                                ?>
                                <option
                                    value="<?php echo $ratePlanId; ?>"
                                    <?php echo (int)($form['rate_plan_id'] ?: 0) === $ratePlanId ? 'selected' : ''; ?>>
                                    <?php echo h($ratePlanLabel); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="form-text">
                            Select the correct contract for this agent, or choose
                            <strong>Public / Rack Rate</strong> to remove the contract assignment.
                            <a href="rate_contracts.php" target="_blank">Manage contracts</a>
                        </div>
                        <div class="alert alert-warning mt-2 mb-0 py-2 small">
                            The <code>rate_contracts</code> layer is not deployed, so each plan
                            here is tied to ONE meal plan. An agent linked to a BB plan cannot
                            price an HB booking and will fall back to the rack rate.
                        </div>
                    <?php else: ?>
                        <div class="alert alert-warning mb-0 py-2">
                            Rate contract editing is unavailable because
                            <code>agents.rate_plan_id</code> or the
                            <code>rate_plans</code> table is missing.
                        </div>
                    <?php endif; ?>
                </div>

                <div class="col-md-6" id="agentGroupRatePlanBlock">
                    <label class="form-label">
                        Group Rate Contract
                        <span class="badge bg-info-subtle text-info-emphasis ms-1">Groups</span>
                    </label>

                    <?php if ($hasAgentGroupContractLink): ?>
                        <select name="group_rate_contract_id" class="form-select">
                            <option value="">Same as standard contract</option>

                            <?php foreach ($rateContracts as $rateContract): ?>
                                <?php
                                $gRcId    = (int)$rateContract['id'];
                                $gRcTitle = trim((string)($rateContract['title'] ?? ''));
                                $gRcCode  = trim((string)($rateContract['code'] ?? ''));
                                $gRcMeals = trim((string)($rateContract['meal_plans'] ?? ''));

                                $gRcLabel = $gRcTitle !== '' ? $gRcTitle : ('Contract #' . $gRcId);
                                if ($gRcCode !== '' && $gRcCode !== $gRcTitle) {
                                    $gRcLabel .= ' (' . $gRcCode . ')';
                                }
                                $gRcLabel .= ' - ' . ($gRcMeals !== '' ? $gRcMeals : 'no rates');
                                ?>
                                <option
                                    value="<?php echo $gRcId; ?>"
                                    <?php echo (int)($form['group_rate_contract_id'] ?: 0) === $gRcId ? 'selected' : ''; ?>>
                                    <?php echo h($gRcLabel); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="form-text">
                            Contract used when a booking qualifies as a <strong>group</strong>.
                            Leave as <strong>Same as standard contract</strong> to price groups
                            on the agent's normal contract above.
                        </div>
                    <?php elseif ($hasAgentGroupRateLink): ?>
                        <select name="group_rate_plan_id" class="form-select">
                            <option value="">Same as standard contract</option>

                            <?php foreach ($ratePlans as $ratePlan): ?>
                                <?php
                                $gRatePlanId = (int)$ratePlan['id'];
                                $gRatePlanTitle = trim((string)($ratePlan['title'] ?? ''));
                                $gRatePlanCode = trim((string)($ratePlan['code'] ?? ''));
                                $gRatePlanLabel = $gRatePlanTitle !== ''
                                    ? $gRatePlanTitle
                                    : ('Rate #' . $gRatePlanId);

                                if ($gRatePlanCode !== '') {
                                    $gRatePlanLabel .= ' (' . $gRatePlanCode . ')';
                                }
                                ?>
                                <option
                                    value="<?php echo $gRatePlanId; ?>"
                                    <?php echo (int)($form['group_rate_plan_id'] ?: 0) === $gRatePlanId ? 'selected' : ''; ?>>
                                    <?php echo h($gRatePlanLabel); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="form-text">
                            Contract used when a booking qualifies as a <strong>group</strong>.
                            Leave as <strong>Same as standard contract</strong> to price groups
                            on the agent's normal contract above.
                        </div>
                    <?php else: ?>
                        <div class="alert alert-warning mb-0 py-2 small">
                            Group rate contract is unavailable because
                            <code>agents.group_rate_contract_id</code> could not be created.
                        </div>
                    <?php endif; ?>
                </div>

                <div class="col-12">
                    <label class="form-label">Remark</label>
                    <textarea name="remark" class="form-control" rows="3"><?php echo h($form['remark']); ?></textarea>
                </div>
            </form>

          <div class="modal-footer">
                <a href="agents.php" class="btn btn-light">Reset</a>
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" form="agentForm" name="save_agent" value="1" class="btn btn-primary">
                    <i class="bi bi-save me-2"></i><?php echo $editing ? 'Update Agent' : 'Save Agent'; ?>
                </button>
          </div>
        </div>
      </div>
    </div>
    <!-- /Add / Edit Agent modal -->

    <div class="card panel-card">
            <div class="card-header">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <h5 class="mb-0">Agents</h5>
                    <form method="get" class="d-flex gap-2">
                        <input type="text" name="q" class="form-control" placeholder="Search agents..." value="<?php echo h($search); ?>">
                        <button class="btn btn-outline-secondary">Search</button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive agent-list-scroll">
                    <table class="table table-modern align-middle mb-0 agent-list-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Agent</th>
                                <th>Rate Contract</th>
                                <th>Office</th>
                                <th>Contact</th>
                                <th>Location</th>
                                <th>VAT No</th>
                                <th>TIN No</th>
                                <th>Payment</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$agents): ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted py-4">No agents found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($agents as $row): ?>
                                    <?php
                                    $locationParts = [];
                                    if (!empty($row['country_name'])) $locationParts[] = $row['country_name'];
                                    if (!empty($row['state_name'])) $locationParts[] = $row['state_name'];
                                    if (!empty($row['city_name'])) $locationParts[] = $row['city_name'];
                                    ?>
                                    <tr>
                                        <td><?php echo (int)$row['id']; ?></td>
                                        <td class="agent-identity-cell">
                                            <div class="agent-primary-name"><?php echo h(agent_full_name($row)); ?></div>
                                            <?php if (!empty($row['address'])): ?>
                                                <div class="agent-address-line" title="<?php echo h($row['address']); ?>">
                                                    <i class="bi bi-geo-alt me-1"></i><?php echo h(preg_replace('/\s+/', ' ', trim((string)$row['address']))); ?>
                                                </div>
                                            <?php endif; ?>
                                            <?php if (!empty($row['email'])): ?>
                                                <div class="agent-email-line">
                                                    <i class="bi bi-envelope me-1"></i><?php echo h($row['email']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php
                                            /* Link with the CONTRACT id when the contract layer is
                                               live. This used to pass rate_plan_id as contract_id -
                                               harmless when they were the same thing, wrong now. */
                                            $rowContractId = !empty($row['rate_contract_id'])
                                                ? (int)$row['rate_contract_id'] : 0;
                                            ?>
                                            <?php if (!empty($row['rate_plan_title'])): ?>
                                                <?php if ($rowContractId > 0): ?>
                                                    <a href="../masters/rate_contracts.php?contract_id=<?php echo $rowContractId; ?>&tab=agents"
                                                       class="badge text-bg-primary text-decoration-none"
                                                       title="Open this rate contract">
                                                        <?php echo h($row['rate_plan_title']); ?>
                                                    </a>
                                                <?php elseif ($hasAgentRateLink && !empty($row['rate_plan_id'])): ?>
                                                    <span class="badge text-bg-primary"><?php echo h($row['rate_plan_title']); ?></span>
                                                <?php else: ?>
                                                    <span class="badge text-bg-primary"><?php echo h($row['rate_plan_title']); ?></span>
                                                <?php endif; ?>

                                                <?php if (!empty($row['rate_contract_meals'])): ?>
                                                    <div class="small text-muted" title="Meal plans this contract holds">
                                                        <?php echo h($row['rate_contract_meals']); ?>
                                                    </div>
                                                <?php elseif (!empty($row['rate_plan_code'])): ?>
                                                    <div class="small text-muted"><?php echo h($row['rate_plan_code']); ?></div>
                                                <?php endif; ?>

                                                <?php if ($hasRateContracts && $rowContractId <= 0 && !empty($row['rate_plan_id'])): ?>
                                                    <div class="small text-warning-emphasis" title="This agent is still on the legacy plan link and can only price one meal plan">
                                                        <i class="bi bi-exclamation-triangle-fill me-1"></i>no contract
                                                    </div>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="badge text-bg-light text-muted border">Public / Rack</span>
                                            <?php endif; ?>

                                            <?php if (!empty($row['group_rate_plan_id']) && !empty($row['group_rate_plan_title'])): ?>
                                                <div class="mt-1">
                                                    <span class="badge text-bg-info-subtle text-info-emphasis border" title="Contract used for group bookings">
                                                        <i class="bi bi-people-fill me-1"></i>Group: <?php echo h($row['group_rate_plan_title']); ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="compact-data-cell">
                                            <?php if (!empty($row['office'])): ?>
                                                <span class="contact-line"><i class="bi bi-whatsapp me-1"></i><?php echo h($row['office']); ?></span>
                                            <?php else: ?>
                                                <span class="empty-value">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="compact-data-cell">
                                            <?php if (!empty($row['mobile'])): ?>
                                                <div class="contact-line"><?php echo h($row['mobile']); ?></div>
                                            <?php endif; ?>
                                            <?php if (!empty($row['phone'])): ?>
                                                <div class="subtle-line"><?php echo h($row['phone']); ?></div>
                                            <?php endif; ?>
                                            <?php if (empty($row['mobile']) && empty($row['phone'])): ?>
                                                <span class="empty-value">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="compact-data-cell">
                                            <?php if ($locationParts): ?>
                                                <div class="location-line"><?php echo h(implode(' · ', $locationParts)); ?></div>
                                            <?php else: ?>
                                                <span class="empty-value">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="tax-reference-cell">
                                            <?php if (!empty($row['vatno'])): ?>
                                                <span class="tax-reference"><?php echo h($row['vatno']); ?></span>
                                            <?php else: ?>
                                                <span class="empty-value">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="tax-reference-cell">
                                            <?php if (!empty($row['tinno'])): ?>
                                                <span class="tax-reference"><?php echo h($row['tinno']); ?></span>
                                            <?php else: ?>
                                                <span class="empty-value">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if (($row['payment_type'] ?? 'on_account') === 'prepayment'): ?>
                                                <span class="badge text-bg-success">Prepayment</span>
                                            <?php else: ?>
                                                <span class="badge text-bg-info">On Account</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="agent-actions">
                                                <button type="button" class="btn btn-sm btn-primary edit-agent-btn" data-agent-id="<?php echo (int)$row['id']; ?>" title="Edit agent">
                                                    <i class="bi bi-pencil-square"></i><span>Edit</span>
                                                </button>
                                                <a href="agents.php?delete=<?php echo (int)$row['id']; ?>"
                                                   class="btn btn-sm btn-outline-danger"
                                                   title="Delete agent"
                                                   onclick="return confirm('Delete this agent permanently? Deletion is allowed only when the agent has no bookings.');">
                                                    <i class="bi bi-trash3"></i><span>Delete</span>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
    </div>
    <!-- /Agents listing card -->
</div>
<!-- /agents-page -->

<script>
document.addEventListener('DOMContentLoaded', function () {
    const countryField = document.getElementById('country_id');
    const stateField = document.getElementById('state_id');
    const cityField = document.getElementById('city_id');
    const form = document.getElementById('agentForm');

    /* ---------------------------------------------------------------
       Add / Edit modal control
       - "New Agent" opens a cleared form.
       - The modal auto-opens when the server is editing an agent
         (?edit=ID) or when a save failed validation, so the user sees
         their in-progress data instead of a hidden form.
       --------------------------------------------------------------- */
    const agentModalEl = document.getElementById('agentModal');
    let agentModal = null;
    if (agentModalEl && window.bootstrap) {
        agentModal = bootstrap.Modal.getOrCreateInstance(agentModalEl);
    }

    function openNewAgent() {
        if (form) {
            form.reset();
            const idField = form.querySelector('input[name="id"]');
            if (idField) idField.value = '0';
        }
        const titleText = document.getElementById('agentModalTitleText');
        if (titleText) titleText.textContent = 'New Agent';
        const ratePlanBlock = document.getElementById('agentRatePlanBlock');
        if (ratePlanBlock) ratePlanBlock.style.display = '';
        const saveBtn = document.querySelector('button[form="agentForm"]');
        if (saveBtn) {
            // Keep the icon, swap the label to "Save Agent".
            saveBtn.innerHTML = '<i class="bi bi-save me-2"></i>Save Agent';
        }
        lastNameManuallyChanged = false;
        if (agentModal) agentModal.show();
    }

    const openNewBtn = document.getElementById('openNewAgentBtn');
    if (openNewBtn) {
        openNewBtn.addEventListener('click', openNewAgent);
    }

    // Auto-open when the server rendered an edit or a validation error.
    <?php if ($editing || !empty($errors)): ?>
    if (agentModal) agentModal.show();
    <?php endif; ?>

    function resetSelect(selectEl, placeholder) {
        if (!selectEl) return;
        selectEl.innerHTML = '';
        const opt = document.createElement('option');
        opt.value = '';
        opt.textContent = placeholder;
        selectEl.appendChild(opt);
    }

    function fillSelect(selectEl, rows, placeholder) {
        resetSelect(selectEl, placeholder);
        rows.forEach(function (row) {
            const opt = document.createElement('option');
            opt.value = row.id;
            opt.textContent = row.name;
            selectEl.appendChild(opt);
        });
    }

    async function loadStates(countryId) {
        resetSelect(stateField, 'Loading states...');
        resetSelect(cityField, 'Select city');

        if (!countryId) {
            resetSelect(stateField, 'Select state');
            return;
        }

        try {
            const resp = await fetch('agents.php?ajax=states&country_id=' + encodeURIComponent(countryId), {
                credentials: 'same-origin'
            });
            const json = await resp.json();
            fillSelect(stateField, json.rows || [], 'Select state');
        } catch (e) {
            resetSelect(stateField, 'Select state');
        }
    }

    async function loadCities(stateId) {
        resetSelect(cityField, 'Loading cities...');

        if (!stateId) {
            resetSelect(cityField, 'Select city');
            return;
        }

        try {
            const resp = await fetch('agents.php?ajax=cities&state_id=' + encodeURIComponent(stateId), {
                credentials: 'same-origin'
            });
            const json = await resp.json();
            fillSelect(cityField, json.rows || [], 'Select city');
        } catch (e) {
            resetSelect(cityField, 'Select city');
        }
    }


    const firstNameField = form ? form.querySelector('[name="firstname"]') : null;
    const lastNameField = form ? form.querySelector('[name="lastname"]') : null;
    let lastNameManuallyChanged = false;

    if (lastNameField) {
        lastNameField.addEventListener('input', function () {
            lastNameManuallyChanged = this.value.trim() !== '' && this.value !== (firstNameField ? firstNameField.value : '');
        });
    }
    if (firstNameField) {
        firstNameField.addEventListener('input', function () {
            if (!lastNameManuallyChanged || !lastNameField.value.trim()) {
                lastNameField.value = this.value;
            }
        });
    }

    function setField(name, value) {
        if (!form) return;
        const field = form.querySelector('[name="' + name + '"]');
        if (field) field.value = value == null ? '' : value;
    }

    async function openEditAgent(agentId, button) {
        if (!agentId || !form) return;
        const original = button ? button.innerHTML : '';
        if (button) {
            button.disabled = true;
            button.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Loading';
        }
        try {
            const resp = await fetch('agents.php?ajax=agent&id=' + encodeURIComponent(agentId), {credentials: 'same-origin'});
            const json = await resp.json();
            if (!json.ok) throw new Error(json.message || 'Could not load agent.');
            const row = json.row || {};
            Object.keys(row).forEach(function (key) { setField(key, row[key]); });
            setField('password', '');

            if (countryField) {
                countryField.value = row.country_id || '';
                await loadStates(row.country_id || '');
                if (stateField) stateField.value = row.state_id || '';
                await loadCities(row.state_id || '');
                if (cityField) cityField.value = row.city_id || '';
            }

            lastNameManuallyChanged = true;
            const titleText = document.getElementById('agentModalTitleText');
            if (titleText) titleText.textContent = 'Edit Agent';
            const saveBtn = document.querySelector('button[form="agentForm"]');
            if (saveBtn) saveBtn.innerHTML = '<i class="bi bi-save me-2"></i>Update Agent';
            if (agentModal) agentModal.show();
        } catch (e) {
            alert(e.message || 'Could not load agent.');
        } finally {
            if (button) { button.disabled = false; button.innerHTML = original; }
        }
    }

    document.querySelectorAll('.edit-agent-btn').forEach(function (button) {
        button.addEventListener('click', function () {
            openEditAgent(this.getAttribute('data-agent-id'), this);
        });
    });

    if (countryField) {
        countryField.addEventListener('change', function () {
            loadStates(this.value);
        });
    }

    if (stateField) {
        stateField.addEventListener('change', function () {
            loadCities(this.value);
        });
    }
});
</script>

<style>
.agents-compact-hero{padding:14px 18px!important;margin-bottom:12px!important;border-radius:18px!important;}
.agents-compact-hero .hero-title{font-size:1.35rem!important;line-height:1.15!important;}
.agents-compact-hero .hero-subtitle{font-size:.88rem!important;max-width:720px!important;}
.agents-page .panel-card{width:100%;}
.agent-list-scroll{max-height:76vh;overflow:auto;}
.agent-list-table thead th{position:sticky;top:0;z-index:10;background:#f8fafc!important;box-shadow:0 1px 0 rgba(15,23,42,.12);white-space:nowrap;}
.agent-list-table tbody td{vertical-align:middle;}

/* Ultra-professional compact agent register */
.agents-page .panel-card {
    border: 1px solid #e6eaf0;
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 8px 30px rgba(15, 23, 42, .055);
}
.agents-page .panel-card .card-header {
    padding: .8rem 1rem;
    background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
    border-bottom: 1px solid #e7ebf0;
}
.agent-list-scroll {
    max-height: calc(100vh - 260px);
    overflow: auto;
}
.agent-list-table {
    width: 100%;
    font-size: .79rem;
    color: #263244;
}
.agent-list-table thead th {
    position: sticky;
    top: 0;
    z-index: 4;
    padding: .58rem .65rem;
    background: #f4f7fb;
    color: #526071;
    border-bottom: 1px solid #dfe5ec;
    font-size: .66rem;
    font-weight: 750;
    letter-spacing: .055em;
    text-transform: uppercase;
    white-space: nowrap;
}
.agent-list-table tbody td {
    padding: .52rem .65rem;
    border-color: #edf0f4;
    vertical-align: middle;
    line-height: 1.24;
}
.agent-list-table tbody tr {
    transition: background-color .15s ease, box-shadow .15s ease;
}
.agent-list-table tbody tr:nth-child(even) {
    background: #fbfcfe;
}
.agent-list-table tbody tr:hover {
    background: #f3f7fc;
    box-shadow: inset 3px 0 0 #376fd0;
}
.agent-list-table th:first-child,
.agent-list-table td:first-child {
    width: 58px;
    color: #7a8797;
    font-variant-numeric: tabular-nums;
}
.agent-list-table th:nth-child(2) {
    min-width: 260px;
}
.agent-list-table th:nth-child(6),
.agent-list-table th:nth-child(7) {
    min-width: 110px;
}
.agent-primary-name {
    color: #172033;
    font-size: .86rem;
    font-weight: 750;
    letter-spacing: -.01em;
    line-height: 1.15;
}
.agent-address-line {
    max-width: 340px;
    margin-top: .18rem;
    overflow: hidden;
    color: #98a2b1;
    font-size: .69rem;
    line-height: 1.2;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.agent-email-line {
    max-width: 300px;
    margin-top: .12rem;
    overflow: hidden;
    color: #718096;
    font-size: .69rem;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.compact-data-cell,
.tax-reference-cell {
    white-space: nowrap;
}
.contact-line {
    color: #344155;
    font-weight: 550;
}
.subtle-line,
.location-line {
    color: #7a8797;
    font-size: .71rem;
}
.tax-reference {
    display: inline-flex;
    align-items: center;
    min-height: 22px;
    padding: .14rem .42rem;
    border: 1px solid #e0e6ee;
    border-radius: 6px;
    background: #f8fafc;
    color: #344155;
    font-size: .7rem;
    font-weight: 650;
    letter-spacing: .015em;
    font-variant-numeric: tabular-nums;
}
.empty-value {
    color: #b2bac5;
}
.agent-list-table .badge {
    padding: .28rem .48rem;
    border-radius: 6px;
    font-size: .66rem;
    font-weight: 650;
    letter-spacing: .01em;
}
.agent-actions {
    display: inline-flex;
    gap: .35rem;
    white-space: nowrap;
}
.agent-actions .btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: .3rem;
    min-height: 29px;
    padding: .25rem .48rem;
    border-radius: 7px;
    font-size: .7rem;
    font-weight: 650;
}
.agent-actions .btn i {
    font-size: .72rem;
}
@media (max-width: 1200px) {
    .agent-actions .btn span {
        display: none;
    }
    .agent-actions .btn {
        width: 30px;
        padding: .25rem;
    }
}

</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>