<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/core/bootstrap.php';

HyroAdminAuth::requireLogin();

$database = HyroDatabase::connection();

$currentAdminPage = 'leads';

$allowedStatuses = [
    '' => 'All Statuses',
    'new' => 'New',
    'contacted' => 'Contacted',
    'demo_scheduled' => 'Demo Scheduled',
    'trial_started' => 'Trial Started',
    'customer' => 'Customer',
    'closed' => 'Closed',
];

$allowedProducts = [
    '' => 'All Products',
    'SPA' => 'HYRO ONE SPA',
    'GYM' => 'HYRO ONE Gym',
    'ACCOUNTING' => 'HYRO ONE Accounting',
    'RETAIL' => 'HYRO ONE Retail',
    'CRM' => 'HYRO ONE CRM',
    'SCHOOL' => 'HYRO ONE School',
];

$search = trim((string) ($_GET['search'] ?? ''));
$product = strtoupper(
    trim((string) ($_GET['product'] ?? ''))
);
$status = strtolower(
    trim((string) ($_GET['status'] ?? ''))
);
$country = trim((string) ($_GET['country'] ?? ''));
$date = trim((string) ($_GET['date'] ?? ''));

if (!array_key_exists($product, $allowedProducts)) {
    $product = '';
}

if (!array_key_exists($status, $allowedStatuses)) {
    $status = '';
}

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$where = [];
$parameters = [];

if ($search !== '') {
    $where[] = '
        (
            lead_code LIKE :search
            OR company_name LIKE :search
            OR contact_name LIKE :search
            OR email LIKE :search
            OR phone LIKE :search
        )
    ';

    $parameters['search'] = '%' . $search . '%';
}

if ($product !== '') {
    $where[] = 'product_code = :product';
    $parameters['product'] = $product;
}

if ($status !== '') {
    $where[] = 'status = :status';
    $parameters['status'] = $status;
}

if ($country !== '') {
    $where[] = 'country_name = :country';
    $parameters['country'] = $country;
}

if ($date !== '') {
    $validDate = DateTimeImmutable::createFromFormat(
        'Y-m-d',
        $date
    );

    if (
        $validDate &&
        $validDate->format('Y-m-d') === $date
    ) {
        $where[] = 'DATE(created_at) = :created_date';
        $parameters['created_date'] = $date;
    } else {
        $date = '';
    }
}

$whereSql = $where === []
    ? ''
    : ' WHERE ' . implode(' AND ', $where);

$countStatement = $database->prepare(
    'SELECT COUNT(*) FROM hyro_leads' . $whereSql
);

$countStatement->execute($parameters);

$totalLeads = (int) $countStatement->fetchColumn();

$totalPages = max(
    1,
    (int) ceil($totalLeads / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

$listSql = '
    SELECT
        id,
        lead_code,
        product_code,
        company_name,
        contact_name,
        email,
        phone,
        country_name,
        preferred_date,
        preferred_time,
        status,
        created_at
    FROM hyro_leads
'
    . $whereSql
    . '
    ORDER BY id DESC
    LIMIT :limit OFFSET :offset
';

$listStatement = $database->prepare($listSql);

foreach ($parameters as $key => $value) {
    $listStatement->bindValue(
        ':' . $key,
        $value,
        PDO::PARAM_STR
    );
}

$listStatement->bindValue(
    ':limit',
    $perPage,
    PDO::PARAM_INT
);

$listStatement->bindValue(
    ':offset',
    $offset,
    PDO::PARAM_INT
);

$listStatement->execute();

$leads = $listStatement->fetchAll();

$countryStatement = $database->query(
    '
    SELECT DISTINCT country_name
    FROM hyro_leads
    WHERE country_name IS NOT NULL
      AND country_name <> ""
    ORDER BY country_name ASC
    '
);

$countries = $countryStatement->fetchAll(
    PDO::FETCH_COLUMN
);

function hyro_lead_query_url(
    int $targetPage,
    array $filters
): string {
    $query = array_filter(
        [
            'search' => $filters['search'] ?? '',
            'product' => $filters['product'] ?? '',
            'status' => $filters['status'] ?? '',
            'country' => $filters['country'] ?? '',
            'date' => $filters['date'] ?? '',
            'page' => $targetPage,
        ],
        static fn (mixed $value): bool =>
            $value !== '' && $value !== null
    );

    return '/experience/admin/leads/index.php?'
        . http_build_query($query);
}

$filters = [
    'search' => $search,
    'product' => $product,
    'status' => $status,
    'country' => $country,
    'date' => $date,
];

$firstResult = $totalLeads === 0
    ? 0
    : $offset + 1;

$lastResult = min(
    $offset + $perPage,
    $totalLeads
);

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <meta
        name="robots"
        content="noindex, nofollow, noarchive"
    >

    <title>Leads | HYRO ONE Admin</title>

    <link
        rel="icon"
        href="/experience/assets/icons/favicon.svg"
        type="image/svg+xml"
    >

    <link
        rel="stylesheet"
        href="/experience/assets/css/site.css?v=<?= time() ?>"
    >

    <link
        rel="stylesheet"
        href="/experience/assets/css/admin.css?v=<?= time() ?>"
    >

</head>

<body class="hyro-admin-body">

<div class="hyro-admin-shell">

    <?php
    require dirname(__DIR__)
        . '/components/admin-header.php';
    ?>

    <?php
    require dirname(__DIR__)
        . '/components/admin-sidebar.php';
    ?>

    <main class="hyro-admin-main">

        <div class="hyro-admin-page-heading">

            <div>

                <h1>Lead Management</h1>

                <p>
                    Search, review and manage all HYRO ONE enquiries.
                </p>

            </div>

            <a
                href="/experience/admin/leads/export.php"
                class="hyro-admin-small-button"
            >
                Export Leads
            </a>

        </div>

        <section class="hyro-lead-filter-panel">

            <form method="get" action="">

                <div class="hyro-lead-filter-grid">

                    <div class="hyro-lead-filter-field">

                        <label for="search">
                            Search
                        </label>

                        <input
                            type="search"
                            id="search"
                            name="search"
                            value="<?= hyro_escape($search) ?>"
                            placeholder="Lead code, company, contact, email or phone"
                        >

                    </div>

                    <div class="hyro-lead-filter-field">

                        <label for="product">
                            Product
                        </label>

                        <select
                            id="product"
                            name="product"
                        >

                            <?php foreach (
                                $allowedProducts as
                                $code => $label
                            ): ?>

                                <option
                                    value="<?= hyro_escape($code) ?>"
                                    <?= $product === $code
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= hyro_escape($label) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                    <div class="hyro-lead-filter-field">

                        <label for="status">
                            Status
                        </label>

                        <select
                            id="status"
                            name="status"
                        >

                            <?php foreach (
                                $allowedStatuses as
                                $code => $label
                            ): ?>

                                <option
                                    value="<?= hyro_escape($code) ?>"
                                    <?= $status === $code
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= hyro_escape($label) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                    <div class="hyro-lead-filter-field">

                        <label for="country">
                            Country
                        </label>

                        <select
                            id="country"
                            name="country"
                        >

                            <option value="">
                                All Countries
                            </option>

                            <?php foreach ($countries as $countryName): ?>

                                <option
                                    value="<?= hyro_escape(
                                        (string) $countryName
                                    ) ?>"
                                    <?= $country === $countryName
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= hyro_escape(
                                        (string) $countryName
                                    ) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                    <div class="hyro-lead-filter-field">

                        <label for="date">
                            Created Date
                        </label>

                        <input
                            type="date"
                            id="date"
                            name="date"
                            value="<?= hyro_escape($date) ?>"
                        >

                    </div>

                </div>

                <div class="hyro-lead-filter-actions">

                    <div class="hyro-lead-filter-buttons">

                        <button
                            type="submit"
                            class="hyro-admin-small-button primary"
                        >
                            Apply Filters
                        </button>

                        <a
                            href="/experience/admin/leads/index.php"
                            class="hyro-admin-small-button"
                        >
                            Clear
                        </a>

                    </div>

                    <div class="hyro-lead-result-count">

                        <?= number_format($totalLeads) ?>
                        lead<?= $totalLeads === 1 ? '' : 's' ?> found

                    </div>

                </div>

            </form>

        </section>

        <section class="hyro-admin-panel">

            <div class="hyro-admin-panel-header">

                <h2>All Leads</h2>

                <span class="hyro-lead-result-count">
                    Page <?= number_format($page) ?>
                    of <?= number_format($totalPages) ?>
                </span>

            </div>

            <?php if ($leads === []): ?>

                <div class="hyro-admin-empty">

                    No leads match the selected filters.

                </div>

            <?php else: ?>

                <div class="hyro-admin-table-wrap">

                    <table class="hyro-admin-table">

                        <thead>

                            <tr>
                                <th>Lead</th>
                                <th>Company</th>
                                <th>Product</th>
                                <th>Phone</th>
                                <th>Country</th>
                                <th>Preferred Demo</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Action</th>
                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($leads as $lead): ?>

                            <?php
                            $leadStatus = strtolower(
                                (string) (
                                    $lead['status'] ?? 'new'
                                )
                            );
                            ?>

                            <tr>

                                <td>

                                    <a
                                        href="/experience/admin/leads/view.php?id=<?= (int) $lead['id'] ?>"
                                        class="hyro-lead-code-link"
                                    >
                                        <?= hyro_escape(
                                            $lead['lead_code']
                                        ) ?>
                                    </a>

                                    <small>
                                        <?= hyro_escape(
                                            $lead['email']
                                        ) ?>
                                    </small>

                                </td>

                                <td>

                                    <strong>
                                        <?= hyro_escape(
                                            $lead['company_name']
                                        ) ?>
                                    </strong>

                                    <small>
                                        <?= hyro_escape(
                                            $lead['contact_name']
                                        ) ?>
                                    </small>

                                </td>

                                <td>
                                    <?= hyro_escape(
                                        $lead['product_code']
                                    ) ?>
                                </td>

                                <td>
                                    <?= hyro_escape(
                                        $lead['phone']
                                    ) ?>
                                </td>

                                <td>
                                    <?= hyro_escape(
                                        $lead['country_name']
                                    ) ?>
                                </td>

                                <td>

                                    <?php if (
                                        !empty($lead['preferred_date'])
                                    ): ?>

                                        <?= hyro_escape(
                                            date(
                                                'd M Y',
                                                strtotime(
                                                    $lead[
                                                        'preferred_date'
                                                    ]
                                                )
                                            )
                                        ) ?>

                                        <small>
                                            <?= hyro_escape(
                                                $lead[
                                                    'preferred_time'
                                                ] ?? ''
                                            ) ?>
                                        </small>

                                    <?php else: ?>

                                        —

                                    <?php endif; ?>

                                </td>

                                <td>

                                    <span
                                        class="hyro-lead-status <?= hyro_escape(
                                            $leadStatus
                                        ) ?>"
                                    >
                                        <?= hyro_escape(
                                            str_replace(
                                                '_',
                                                ' ',
                                                $leadStatus
                                            )
                                        ) ?>
                                    </span>

                                </td>

                                <td>

                                    <?= hyro_escape(
                                        date(
                                            'd M Y',
                                            strtotime(
                                                $lead['created_at']
                                            )
                                        )
                                    ) ?>

                                    <small>
                                        <?= hyro_escape(
                                            date(
                                                'h:i A',
                                                strtotime(
                                                    $lead['created_at']
                                                )
                                            )
                                        ) ?>
                                    </small>

                                </td>

                                <td>

                                    <a
                                        href="/experience/admin/leads/view.php?id=<?= (int) $lead['id'] ?>"
                                        class="hyro-admin-view-button"
                                    >
                                        View
                                    </a>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

                <div class="hyro-admin-pagination">

                    <div class="hyro-admin-pagination-info">

                        Showing
                        <?= number_format($firstResult) ?>
                        to
                        <?= number_format($lastResult) ?>
                        of
                        <?= number_format($totalLeads) ?>
                        leads

                    </div>

                    <div class="hyro-admin-pagination-links">

                        <?php if ($page > 1): ?>

                            <a href="<?= hyro_escape(
                                hyro_lead_query_url(
                                    $page - 1,
                                    $filters
                                )
                            ) ?>">
                                Previous
                            </a>

                        <?php else: ?>

                            <span class="disabled">
                                Previous
                            </span>

                        <?php endif; ?>

                        <?php
                        $startPage = max(1, $page - 2);
                        $endPage = min(
                            $totalPages,
                            $page + 2
                        );

                        for (
                            $pageNumber = $startPage;
                            $pageNumber <= $endPage;
                            $pageNumber++
                        ):
                        ?>

                            <?php if ($pageNumber === $page): ?>

                                <span class="active">
                                    <?= $pageNumber ?>
                                </span>

                            <?php else: ?>

                                <a href="<?= hyro_escape(
                                    hyro_lead_query_url(
                                        $pageNumber,
                                        $filters
                                    )
                                ) ?>">
                                    <?= $pageNumber ?>
                                </a>

                            <?php endif; ?>

                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>

                            <a href="<?= hyro_escape(
                                hyro_lead_query_url(
                                    $page + 1,
                                    $filters
                                )
                            ) ?>">
                                Next
                            </a>

                        <?php else: ?>

                            <span class="disabled">
                                Next
                            </span>

                        <?php endif; ?>

                    </div>

                </div>

            <?php endif; ?>

        </section>

    </main>

</div>

<script
    src="/experience/assets/js/admin.js?v=<?= time() ?>"
></script>

</body>
</html>