<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/includes/layout.php';
require_once dirname(__DIR__) . '/includes/report-data.php';

function crm_fu_text(string $key): string
{
    return trim((string)($_GET[$key] ?? ''));
}

function crm_fu_int(string $key): int
{
    $value = crm_fu_text($key);
    return ctype_digit($value) ? (int)$value : 0;
}

function crm_fu_date(string $key): string
{
    $value = crm_fu_text($key);
    return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1 ? $value : '';
}

function crm_fu_options(mysqli $db, string $table, string $label, string $extra = '', string $order = ''): array
{
    if (!crm_report_table($db, $table)) {
        return [];
    }
    $columns = $extra === '' ? "id,{$label} label" : "id,{$label} label,{$extra}";
    return crm_report_query($db, "SELECT {$columns} FROM {$table} ORDER BY " . ($order !== '' ? $order : $label));
}

function crm_fu_url(array $overrides = []): string
{
    $query = array_merge($_GET, $overrides);
    foreach ($query as $key => $value) {
        if ($value === '' || $value === null) {
            unset($query[$key]);
        }
    }
    return '?' . http_build_query($query);
}

function crm_fu_badge(string $status): string
{
    $status = strtolower($status);
    if (preg_match('/convert|won|success/', $status)) return 'green';
    if (preg_match('/lost|cancel|reject|negative/', $status)) return 'red';
    if (preg_match('/follow|pending|hold|progress/', $status)) return 'amber';
    return 'blue';
}

$requestPath = ltrim((string)(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: ''), '/');
require_login();
require_acl('can_view', $requestPath);

$db = crm_report_db();
$error = '';
$rows = [];
$summary = ['total' => 0, 'due_today' => 0, 'overdue' => 0, 'upcoming' => 0];
$page = max(1, crm_fu_int('page'));
$limitInput = crm_fu_text('limit');
$limit = $limitInput === 'all' ? 0 : (int)($limitInput !== '' ? $limitInput : 50);
if (!in_array($limit, [25, 50, 100, 200, 0], true)) $limit = 50;
$isExport = crm_fu_text('export') === 'csv';

$filters = [
    'from' => crm_fu_date('from'),
    'to' => crm_fu_date('to'),
    'company' => crm_fu_text('company'),
    'source' => crm_fu_int('source'),
    'nature' => crm_fu_int('nature'),
    'status' => crm_fu_int('status'),
    'priority' => crm_fu_int('priority'),
    'segment' => crm_fu_text('segment') === '0' ? '0' : crm_fu_int('segment'),
    'state' => crm_fu_text('state') === '0' ? '0' : crm_fu_int('state'),
    'district' => crm_fu_text('district') === '0' ? '0' : crm_fu_int('district'),
    'taluka' => crm_fu_text('taluka') === '0' ? '0' : crm_fu_int('taluka'),
    'locality' => crm_fu_text('locality') === '0' ? '0' : crm_fu_int('locality'),
    'owner' => crm_fu_int('owner'),
    'product' => crm_fu_int('product'),
    'scope' => in_array(crm_fu_text('scope'), ['due', 'overdue', 'upcoming', 'unscheduled'], true) ? crm_fu_text('scope') : '',
];

$sources = $natures = $statuses = $priorities = $segments = $states = [];
$districts = $talukas = $localities = $owners = $products = [];
$total = 0;
$pages = 1;

try {
    if (!$db) throw new RuntimeException('ABOX database connection is unavailable.');

    $sources = crm_fu_options($db, 'jos_crm_mleadsource', 'leadsource', '', 'leadsource');
    $natures = crm_fu_options($db, 'jos_crm_mleadtypes', 'name');
    $statuses = crm_fu_options($db, 'jos_crm_mleadstatus', 'name', '', 'orderid,name');
    $priorities = crm_fu_options($db, 'jos_crm_priority', 'name');
    $segments = crm_fu_options($db, 'jos_crm_segmentmaster', 'segment');
    $states = crm_fu_options($db, 'jos_crm_mstates', 'name');
    $districts = crm_fu_options($db, 'jos_crm_district', 'name', 'stateid');
    $talukas = crm_fu_options($db, 'jos_crm_mcitys', 'name', 'stateid,districtid');
    $localities = crm_fu_options($db, 'jos_crm_locality', 'name', 'stateid,districtid,talukaid');
    $products = crm_fu_options($db, 'jos_crm_crmproducts', 'name');
    $hasUsers = crm_report_table($db, 'jos_users');
    $owners = $hasUsers
        ? crm_report_query($db, 'SELECT id,name label FROM jos_users ORDER BY name')
        : crm_report_query($db, "SELECT DISTINCT created_by id,CONCAT('User #',created_by) label FROM jos_crm_leadentry ORDER BY created_by");

    $baseWhere = ['1=1'];
    if ($filters['from'] !== '') $baseWhere[] = "DATE(a.followupdate)>='" . $db->real_escape_string($filters['from']) . "'";
    if ($filters['to'] !== '') $baseWhere[] = "DATE(a.followupdate)<='" . $db->real_escape_string($filters['to']) . "'";
    if ($filters['company'] !== '') {
        $company = $db->real_escape_string($filters['company']);
        $baseWhere[] = "(c.companyname LIKE '%{$company}%' OR c.contactperson1 LIKE '%{$company}%')";
    }
    foreach (['source' => 'a.leadsource', 'nature' => 'a.leadtype', 'status' => 'a.leadstatus',
              'priority' => 'a.priority', 'owner' => 'a.created_by'] as $filter => $field) {
        if ((int)$filters[$filter] > 0) $baseWhere[] = "{$field}=" . (int)$filters[$filter];
    }
    foreach (['segment' => 'c.segment', 'state' => 'c.stateid', 'district' => 'c.districtid',
              'taluka' => 'c.talukaid', 'locality' => 'c.localityid'] as $filter => $field) {
        if ($filters[$filter] === '0') $baseWhere[] = "COALESCE({$field},0)=0";
        elseif ((int)$filters[$filter] > 0) $baseWhere[] = "{$field}=" . (int)$filters[$filter];
    }
    if ($filters['product'] > 0) {
        $baseWhere[] = "EXISTS (SELECT 1 FROM jos_crm_leadentry_grid pg WHERE pg.leadid=a.id AND pg.propid=" . (int)$filters['product'] . ')';
    }
    $baseWhereSql = implode(' AND ', $baseWhere);
    $summary = crm_report_query(
        $db,
        "SELECT COUNT(*) total,
                SUM(DATE(a.followupdate)=CURDATE()) due_today,
                SUM(DATE(a.followupdate)<CURDATE() AND DATE(a.followupdate)>'1970-01-01') overdue,
                SUM(DATE(a.followupdate)>CURDATE() AND DATE(a.followupdate)<=DATE_ADD(CURDATE(),INTERVAL 7 DAY)) upcoming
         FROM jos_crm_leadentry a LEFT JOIN jos_crm_mcustomers c ON c.id=a.custid WHERE {$baseWhereSql}"
    )[0];

    $where = $baseWhere;
    if ($filters['scope'] === 'due') $where[] = 'DATE(a.followupdate)=CURDATE()';
    elseif ($filters['scope'] === 'overdue') $where[] = "DATE(a.followupdate)<CURDATE() AND DATE(a.followupdate)>'1970-01-01'";
    elseif ($filters['scope'] === 'upcoming') $where[] = 'DATE(a.followupdate)>CURDATE() AND DATE(a.followupdate)<=DATE_ADD(CURDATE(),INTERVAL 7 DAY)';
    elseif ($filters['scope'] === 'unscheduled') $where[] = "(DATE(a.followupdate) IS NULL OR DATE(a.followupdate)<='1970-01-01')";
    $whereSql = implode(' AND ', $where);

    $total = (int)crm_report_value(
        $db,
        "SELECT COUNT(*) value FROM jos_crm_leadentry a LEFT JOIN jos_crm_mcustomers c ON c.id=a.custid WHERE {$whereSql}"
    );
    $pages = $limit > 0 ? max(1, (int)ceil($total / $limit)) : 1;
    $page = min($page, $pages);
    $offset = $limit > 0 ? ($page - 1) * $limit : 0;
    $limitSql = (!$isExport && $limit > 0) ? " LIMIT {$offset},{$limit}" : '';
    $userJoin = $hasUsers ? 'LEFT JOIN jos_users u ON u.id=a.created_by' : '';
    $ownerName = $hasUsers
        ? "COALESCE(NULLIF(u.name,''),IF(a.created_by>0,CONCAT('User #',a.created_by),'Unassigned'))"
        : "IF(a.created_by>0,CONCAT('User #',a.created_by),'Unassigned')";

    $rows = crm_report_query(
        $db,
        "SELECT a.id,a.date,a.followupdate,DATEDIFF(DATE(a.followupdate),CURDATE()) follow_days,a.description,a.total,
                COALESCE(NULLIF(c.companyname,''),IF(a.custid>0,CONCAT('Customer #',a.custid),'Unassigned customer')) company,
                COALESCE(c.address,'') address,COALESCE(c.contactperson1,'') contactperson,
                COALESCE(NULLIF(c.contactno1,''),NULLIF(c.officecontact,''),NULLIF(c.contactnumber,''),'') contact,
                COALESCE(c.emprange,'') employee_range,
                COALESCE(NULLIF(src.leadsource,''),'-') source,
                COALESCE(NULLIF(nt.name,''),'-') nature,
                COALESCE(NULLIF(st.name,''),IF(a.leadstatus>0,CONCAT('Status #',a.leadstatus),'Not assigned')) status,
                COALESCE(NULLIF(pr.name,''),'-') priority,
                COALESCE(NULLIF(seg.segment,''),'-') segment,
                COALESCE(NULLIF(ms.name,''),'') state_name,
                COALESCE(NULLIF(md.name,''),'') district_name,
                COALESCE(NULLIF(mt.name,''),'') taluka_name,
                {$ownerName} owner_name,
                (SELECT COUNT(*) FROM jos_crm_lead_followup_grid f WHERE f.leadid=a.id) follow_count,
                COALESCE((SELECT f.conversation FROM jos_crm_lead_followup_grid f WHERE f.leadid=a.id ORDER BY f.id DESC LIMIT 1),'') latest_conversation,
                COALESCE((SELECT f.sysdate FROM jos_crm_lead_followup_grid f WHERE f.leadid=a.id ORDER BY f.id DESC LIMIT 1),'') latest_activity,
                (SELECT COUNT(*) FROM jos_crm_quotations q WHERE q.leadid=a.id) quote_count,
                COALESCE((SELECT SUM(q.total) FROM jos_crm_quotations q WHERE q.leadid=a.id),0) quote_total,
                COALESCE((SELECT GROUP_CONCAT(DISTINCT COALESCE(NULLIF(p.name,''),IF(g.propid>0,CONCAT('Product #',g.propid),'Unassigned product')) ORDER BY p.name SEPARATOR ', ')
                          FROM jos_crm_leadentry_grid g LEFT JOIN jos_crm_crmproducts p ON p.id=g.propid WHERE g.leadid=a.id),'') product_names
         FROM jos_crm_leadentry a
         LEFT JOIN jos_crm_mcustomers c ON c.id=a.custid
         LEFT JOIN jos_crm_mleadsource src ON src.id=a.leadsource
         LEFT JOIN jos_crm_mleadtypes nt ON nt.id=a.leadtype
         LEFT JOIN jos_crm_mleadstatus st ON st.id=a.leadstatus
         LEFT JOIN jos_crm_priority pr ON pr.id=a.priority
         LEFT JOIN jos_crm_segmentmaster seg ON seg.id=c.segment
         LEFT JOIN jos_crm_mstates ms ON ms.id=c.stateid
         LEFT JOIN jos_crm_district md ON md.id=c.districtid
         LEFT JOIN jos_crm_mcitys mt ON mt.id=c.talukaid
         {$userJoin}
         WHERE {$whereSql}
         ORDER BY CASE WHEN DATE(a.followupdate) IS NULL OR DATE(a.followupdate)<='1970-01-01' THEN 1 ELSE 0 END,
                  a.followupdate ASC,a.id DESC{$limitSql}"
    );
} catch (Throwable $exception) {
    $error = $exception->getMessage();
}

if ($isExport && $error === '') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="follow-up-summary-' . date('Y-m-d') . '.csv"');
    $stream = fopen('php://output', 'wb');
    if ($stream !== false) {
        fwrite($stream, "\xEF\xBB\xBF");
        fputcsv($stream, ['Lead No', 'Lead Date', 'Company', 'Contact', 'Source', 'Nature', 'Status', 'Priority', 'Products', 'Owner', 'Next Follow-up', 'Conversation', 'Follow-ups']);
        foreach ($rows as $row) {
            fputcsv($stream, [
                'LEAD-' . $row['id'], $row['date'], $row['company'], $row['contact'], $row['source'],
                $row['nature'], $row['status'], $row['priority'], $row['product_names'], $row['owner_name'],
                $row['followupdate'], $row['latest_conversation'], $row['follow_count'],
            ]);
        }
        fclose($stream);
    }
    exit;
}

$shownFrom = $total > 0 ? ($limit > 0 ? (($page - 1) * $limit + 1) : 1) : 0;
$shownTo = $limit > 0 ? min($total, $page * $limit) : $total;
$activeFilters = array_filter($filters, static fn($value): bool => $value !== '' && $value !== 0);
crm_page_start('Follow-up Summary', 'reports', 'Legacy-compatible CRM follow-up worklist');
?>
<section class="lead-command-bar followup-command-bar">
    <div><strong><?= crm_e(number_format($total)) ?> follow-up <?= $total === 1 ? 'lead' : 'leads' ?></strong>
        <span>Showing <?= crm_e(number_format($shownFrom)) ?>&ndash;<?= crm_e(number_format($shownTo)) ?> from the live CRM worklist</span></div>
    <div class="inline-actions">
        <button class="button secondary small" type="button" onclick="window.print()"><i class="fa-solid fa-print"></i> Print</button>
        <a class="button secondary small" href="<?= crm_e(crm_fu_url(['export' => 'csv', 'page' => null])) ?>"><i class="fa-solid fa-file-export"></i> Export CSV</a>
    </div>
</section>

<section class="kpi-grid followup-kpis">
    <a class="card kpi" href="<?= crm_e(crm_fu_url(['scope' => null, 'page' => null])) ?>"><span>Total Leads</span><strong><?= crm_e(number_format((int)$summary['total'])) ?></strong><small>Selected filters</small></a>
    <a class="card kpi" href="<?= crm_e(crm_fu_url(['scope' => 'due', 'page' => null])) ?>"><span>Due Today</span><strong><?= crm_e(number_format((int)$summary['due_today'])) ?></strong><small>Requires action today</small></a>
    <a class="card kpi" href="<?= crm_e(crm_fu_url(['scope' => 'overdue', 'page' => null])) ?>"><span>Overdue</span><strong><?= crm_e(number_format((int)$summary['overdue'])) ?></strong><small>Past follow-up date</small></a>
    <a class="card kpi" href="<?= crm_e(crm_fu_url(['scope' => 'upcoming', 'page' => null])) ?>"><span>Upcoming</span><strong><?= crm_e(number_format((int)$summary['upcoming'])) ?></strong><small>Next seven days</small></a>
</section>

<details class="card lead-filter-card" <?= $activeFilters !== [] ? 'open' : '' ?>>
    <summary><span><i class="fa-solid fa-filter"></i> Follow-up Filters</span><small><?= $activeFilters === [] ? 'Date, company, pipeline, location, owner and product' : count($activeFilters) . ' filters applied' ?></small><i class="fa-solid fa-chevron-down filter-chevron"></i></summary>
    <form class="lead-filter-form" method="get">
        <div class="lead-filter-grid followup-filter-grid">
            <div class="field"><label>Follow-up From</label><input class="control" type="date" name="from" value="<?= crm_e($filters['from']) ?>"></div>
            <div class="field"><label>Follow-up To</label><input class="control" type="date" name="to" value="<?= crm_e($filters['to']) ?>"></div>
            <div class="field wide"><label>Company / Contact</label><input class="control" name="company" value="<?= crm_e($filters['company']) ?>" placeholder="Search company or contact"></div>
            <?php
            $selects = [
                ['source', 'Lead Source', $sources], ['nature', 'Lead Nature', $natures],
                ['status', 'Lead Status', $statuses], ['priority', 'Priority', $priorities],
                ['segment', 'Segment', $segments], ['owner', 'User', $owners], ['product', 'Product', $products],
            ];
            foreach ($selects as [$name, $label, $options]): ?>
                <div class="field"><label><?= crm_e($label) ?></label><select class="control" name="<?= crm_e($name) ?>"><option value="">All</option>
                    <?php foreach ($options as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (string)$filters[$name] === (string)$option['id'] ? 'selected' : '' ?>><?= crm_e($option['label']) ?></option><?php endforeach; ?>
                </select></div>
            <?php endforeach; ?>
            <div class="field"><label>State</label><select class="control" id="fu-state" name="state"><option value="">All States</option><?php foreach ($states as $option): ?><option value="<?= (int)$option['id'] ?>" <?= (string)$filters['state'] === (string)$option['id'] ? 'selected' : '' ?>><?= crm_e($option['label']) ?></option><?php endforeach; ?></select></div>
            <div class="field"><label>District</label><select class="control" id="fu-district" name="district"><option value="">All Districts</option><?php foreach ($districts as $option): ?><option value="<?= (int)$option['id'] ?>" data-state="<?= (int)$option['stateid'] ?>" <?= (string)$filters['district'] === (string)$option['id'] ? 'selected' : '' ?>><?= crm_e($option['label']) ?></option><?php endforeach; ?></select></div>
            <div class="field"><label>Taluka</label><select class="control" id="fu-taluka" name="taluka"><option value="">All Talukas</option><?php foreach ($talukas as $option): ?><option value="<?= (int)$option['id'] ?>" data-state="<?= (int)$option['stateid'] ?>" data-district="<?= (int)$option['districtid'] ?>" <?= (string)$filters['taluka'] === (string)$option['id'] ? 'selected' : '' ?>><?= crm_e($option['label']) ?></option><?php endforeach; ?></select></div>
            <div class="field"><label>Locality</label><select class="control" id="fu-locality" name="locality"><option value="">All Localities</option><?php foreach ($localities as $option): ?><option value="<?= (int)$option['id'] ?>" data-state="<?= (int)$option['stateid'] ?>" data-district="<?= (int)$option['districtid'] ?>" data-taluka="<?= (int)$option['talukaid'] ?>" <?= (string)$filters['locality'] === (string)$option['id'] ? 'selected' : '' ?>><?= crm_e($option['label']) ?></option><?php endforeach; ?></select></div>
            <div class="field"><label>Rows</label><select class="control" name="limit"><?php foreach ([25,50,100,200] as $size): ?><option value="<?= $size ?>" <?= $limit === $size ? 'selected' : '' ?>><?= $size ?></option><?php endforeach; ?><option value="all" <?= $limit === 0 ? 'selected' : '' ?>>All</option></select></div>
        </div>
        <input type="hidden" name="scope" value="<?= crm_e($filters['scope']) ?>">
        <div class="lead-filter-actions"><a class="button secondary" href="<?= crm_e(crm_url('reports/follow-up.php')) ?>"><i class="fa-solid fa-rotate"></i> Reset</a><button class="button primary" type="submit"><i class="fa-solid fa-magnifying-glass"></i> Apply Filters</button></div>
    </form>
</details>

<?php if ($error !== ''): ?><div class="report-notice"><i class="fa-solid fa-circle-exclamation"></i><span><?= crm_e($error) ?></span></div><?php endif; ?>

<section class="followup-list">
<?php if ($rows === [] && $error === ''): ?>
    <div class="card lead-empty"><i class="fa-solid fa-calendar-xmark"></i><h2>No follow-ups found</h2><p>Try changing the selected date or pipeline filters.</p></div>
<?php endif; ?>
<?php foreach ($rows as $index => $row): ?>
    <?php
    $followTime = strtotime((string)$row['followupdate']);
    $validFollow = $followTime !== false && (int)date('Y', $followTime) > 1970;
    $leadTime = strtotime((string)$row['date']);
    $validLeadDate = $leadTime !== false && (int)date('Y', $leadTime) > 1970;
    $leadDateLabel = $validLeadDate ? date('d M Y', $leadTime) : 'Not recorded';
    $days = $validFollow ? (int)$row['follow_days'] : null;
    $dueLabel = !$validFollow ? 'Not Scheduled' : ($days < 0 ? abs($days) . ' day' . (abs($days) === 1 ? '' : 's') . ' overdue' : ($days === 0 ? 'Due Today' : 'Due in ' . $days . ' day' . ($days === 1 ? '' : 's')));
    $dueClass = !$validFollow ? 'blue' : ($days < 0 ? 'red' : ($days === 0 ? 'amber' : 'green'));
    $location = implode(', ', array_filter([$row['state_name'], $row['district_name'], $row['taluka_name']]));
    ?>
    <article class="followup-card">
        <header class="followup-card-head">
            <div class="lead-identity"><span class="lead-sequence"><?= (int)($shownFrom + $index) ?></span><div>
                <div class="lead-title-line"><h2><?= crm_e($row['company']) ?></h2><span class="badge <?= crm_e(crm_fu_badge($row['status'])) ?>"><?= crm_e($row['status']) ?></span><span class="badge <?= crm_e($dueClass) ?>"><?= crm_e($dueLabel) ?></span></div>
                <p>LEAD-<?= (int)$row['id'] ?> &bull; Lead Date <?= crm_e($leadDateLabel) ?> &bull; <?= crm_e($row['nature']) ?></p>
            </div></div>
            <div class="followup-date-box"><small>Next Follow-up</small><strong><?= $validFollow ? crm_e(date('d M Y', $followTime)) : 'Not scheduled' ?></strong></div>
        </header>
        <div class="followup-card-grid">
            <div class="lead-detail-block"><i class="fa-solid fa-address-book"></i><div><small>Contact</small><strong><?= crm_e($row['contactperson'] ?: 'Not assigned') ?></strong><?php if ($row['contact'] !== ''): ?><a href="tel:<?= crm_e($row['contact']) ?>"><?= crm_e($row['contact']) ?></a><?php endif; ?><p><?= crm_e($row['employee_range'] !== '' ? $row['employee_range'] . ' employees' : '') ?></p></div></div>
            <div class="lead-detail-block"><i class="fa-solid fa-location-dot"></i><div><small>Location</small><strong><?= crm_e($location !== '' ? $location : 'Not assigned') ?></strong><p><?= crm_e($row['address']) ?></p></div></div>
            <div class="lead-detail-block"><i class="fa-solid fa-diagram-project"></i><div><small>Classification</small><strong><?= crm_e($row['source']) ?></strong><p><?= crm_e($row['priority']) ?> priority &bull; <?= crm_e($row['segment']) ?></p></div></div>
            <div class="lead-detail-block"><i class="fa-solid fa-boxes-stacked"></i><div><small>Products</small><strong><?= crm_e($row['product_names'] !== '' ? $row['product_names'] : 'No products') ?></strong><p>Lead value <?= crm_e(crm_money($row['total'])) ?></p></div></div>
        </div>
        <div class="followup-conversation">
            <i class="fa-solid fa-comments"></i><div><small>Latest Conversation (<?= (int)$row['follow_count'] ?>)</small><span><?= crm_e($row['latest_conversation'] !== '' ? $row['latest_conversation'] : ($row['description'] ?: 'No conversation recorded')) ?></span></div>
        </div>
        <footer class="lead-card-actions">
            <span class="followup-owner"><i class="fa-solid fa-user"></i> <?= crm_e($row['owner_name']) ?></span>
            <a class="button secondary small" href="<?= crm_e(crm_url('operations/leads.php?lead_no=' . (int)$row['id'])) ?>"><i class="fa-solid fa-eye"></i> View Lead</a>
            <a class="button secondary small" href="<?= crm_e(crm_url('reports/lead-map.php?lead=' . (int)$row['id'])) ?>"><i class="fa-solid fa-map-location-dot"></i> Map</a>
            <?php if ((int)$row['quote_count'] > 0): ?><span class="lead-quote-state"><i class="fa-solid fa-file-invoice"></i> <?= (int)$row['quote_count'] ?> quotation<?= (int)$row['quote_count'] === 1 ? '' : 's' ?> &bull; <?= crm_e(crm_money($row['quote_total'])) ?></span><?php endif; ?>
        </footer>
    </article>
<?php endforeach; ?>
</section>

<?php if ($pages > 1): ?><nav class="lead-pagination" aria-label="Follow-up pagination"><span>Page <?= $page ?> of <?= $pages ?></span><div><?php if ($page > 1): ?><a class="button secondary small" href="<?= crm_e(crm_fu_url(['page' => $page - 1])) ?>"><i class="fa-solid fa-chevron-left"></i> Previous</a><?php endif; ?><?php if ($page < $pages): ?><a class="button secondary small" href="<?= crm_e(crm_fu_url(['page' => $page + 1])) ?>">Next <i class="fa-solid fa-chevron-right"></i></a><?php endif; ?></div></nav><?php endif; ?>

<script>
(() => {
    const state = document.getElementById('fu-state');
    const district = document.getElementById('fu-district');
    const taluka = document.getElementById('fu-taluka');
    const locality = document.getElementById('fu-locality');
    const filter = (select, tests) => {
        if (!select) return;
        [...select.options].forEach((option, index) => {
            if (index === 0) return;
            const visible = Object.entries(tests).every(([key, value]) => value === '' || option.dataset[key] === value);
            option.hidden = !visible; option.disabled = !visible;
        });
        if (select.selectedOptions[0]?.disabled) select.value = '';
    };
    const syncLocality = () => filter(locality, {state: state?.value || '', district: district?.value || '', taluka: taluka?.value || ''});
    const syncTaluka = () => { filter(taluka, {state: state?.value || '', district: district?.value || ''}); syncLocality(); };
    const syncDistrict = () => { filter(district, {state: state?.value || ''}); syncTaluka(); };
    state?.addEventListener('change', syncDistrict); district?.addEventListener('change', syncTaluka); taluka?.addEventListener('change', syncLocality); syncDistrict();
})();
</script>
<?php crm_page_end(); ?>
