<?= $this->extend('layouts/enterprise') ?>

<?= $this->section('content') ?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Transport',
    'workspaceCrumbCurrent' => 'Generate Plan',
    'workspaceTitle'        => 'Generate AI Transport Plan',
    'workspaceDesc'         => 'The AI uses contract sites, assigned staff, and shift timing to propose garage-to-site routes and driver schedules.',
]) ?>

<div class="row g-3 mb-4">
    <?php
    $ready = [
        ['label' => 'Contract sites configured', 'value' => $readiness['contract_sites'], 'icon' => 'fa-building-flag', 'href' => 'transport/ai/contract-sites'],
        ['label' => 'Staff assigned on contracts', 'value' => $readiness['assigned_staff'], 'icon' => 'fa-users', 'href' => 'contracts'],
        ['label' => 'Sites with default shift', 'value' => $readiness['sites_with_shift'], 'icon' => 'fa-clock', 'href' => 'transport/ai/contract-sites'],
        ['label' => 'Vehicles with capacity', 'value' => $readiness['vehicles'], 'icon' => 'fa-truck', 'href' => 'transport/vehicles'],
        ['label' => 'Active drivers', 'value' => $readiness['drivers'], 'icon' => 'fa-id-card', 'href' => 'transport/drivers'],
    ];
    ?>
    <?php foreach ($ready as $item): ?>
        <div class="col">
            <article class="enterprise-kpi-card <?= $item['value'] === 0 ? 'border border-danger' : '' ?>">
                <div class="enterprise-kpi-header">
                    <span class="enterprise-kpi-label"><?= esc($item['label']) ?></span>
                    <span class="enterprise-kpi-icon"><i class="fa-solid <?= esc($item['icon']) ?>"></i></span>
                </div>
                <div class="enterprise-kpi-value"><?= (int) $item['value'] ?></div>
                <a href="<?= base_url($item['href']) ?>" class="small">Manage</a>
            </article>
        </div>
    <?php endforeach; ?>
</div>

<article class="enterprise-settings-card" style="max-width:860px;">
    <div class="enterprise-settings-card__head">
        <i class="fa-solid fa-wand-magic-sparkles"></i>
        <h2 class="enterprise-settings-card__title">Plan Parameters</h2>
    </div>

    <?= $this->include('Modules\Transport\Views\partials\form_errors') ?>

    <form action="<?= base_url('transport/ai/plans/generate') ?>" method="get" class="mb-3" id="ai-plan-scope-form">
        <div class="enterprise-settings-fields">
            <div class="enterprise-field">
                <label class="enterprise-field-label">Region</label>
                <select name="region" class="form-select form-select-sm" id="ai-plan-region">
                    <option value="">All regions</option>
                    <?php foreach ($regions as $r): ?>
                        <option value="<?= esc($r['region']) ?>" <?= ($region ?? '') === $r['region'] ? 'selected' : '' ?>>
                            <?= esc($r['region']) ?> (<?= (int) $r['site_count'] ?> sites)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="enterprise-field">
                <label class="enterprise-field-label">Batch size</label>
                <div class="btn-group btn-group-sm w-100" role="group" aria-label="Batch size">
                    <?php foreach ($batchLimits as $limit): ?>
                        <input type="radio" class="btn-check" name="batch_limit" id="batch_<?= $limit ?>"
                               value="<?= $limit ?>" <?= (int) ($batchLimit ?? 40) === $limit ? 'checked' : '' ?>>
                        <label class="btn btn-outline-secondary" for="batch_<?= $limit ?>"><?= $limit ?></label>
                    <?php endforeach; ?>
                </div>
                <div class="form-text">Max contracts planned in one run.</div>
            </div>
            <div class="enterprise-field enterprise-field--full">
                <label class="enterprise-field-label">Filter contracts</label>
                <input type="text" name="contract_q" class="form-control form-control-sm"
                       value="<?= esc($contractSearch ?? '') ?>"
                       placeholder="Search by number, title, or site name">
            </div>
        </div>
        <div class="d-flex align-items-center gap-2 flex-wrap">
            <button type="submit" class="btn btn-sm btn-outline-primary">Apply region / batch</button>
            <?php if ($region): ?>
                <span class="text-muted small">
                    <?= esc($region) ?>: <?= (int) $siteTotal ?> site<?= (int) $siteTotal === 1 ? '' : 's' ?>
                    <?php if ((int) $siteTotal > (int) $batchLimit): ?>
                        — first <?= (int) $batchLimit ?> will be auto-selected
                    <?php endif; ?>
                </span>
            <?php endif; ?>
        </div>
    </form>

    <form action="<?= base_url('transport/ai/plans') ?>" method="post" novalidate id="ai-plan-generate-form">
        <?= csrf_field() ?>
        <input type="hidden" name="region" value="<?= esc($region ?? '') ?>">
        <input type="hidden" name="batch_limit" value="<?= (int) ($batchLimit ?? 40) ?>">
        <div class="enterprise-settings-fields">
            <div class="enterprise-field enterprise-field--full">
                <label class="enterprise-field-label">Plan Title</label>
                <input type="text" name="title" class="form-control" maxlength="200"
                       value="<?= esc(old('title', '')) ?>"
                       placeholder="Optional — a descriptive title is generated when left empty">
            </div>
            <div class="enterprise-field">
                <label class="enterprise-field-label">Start Date <span class="text-danger">*</span></label>
                <input type="date" name="plan_start_date" class="form-control" required
                       value="<?= esc(old('plan_start_date', date('Y-m-d', strtotime('+1 day')))) ?>">
            </div>
            <div class="enterprise-field">
                <label class="enterprise-field-label">End Date <span class="text-danger">*</span></label>
                <input type="date" name="plan_end_date" class="form-control" required
                       value="<?= esc(old('plan_end_date', date('Y-m-d', strtotime('+1 day')))) ?>">
                <div class="form-text">Up to 31 days. Pick the same date for a daily plan or a Monday–Sunday range for a weekly plan.</div>
            </div>
            <div class="enterprise-field enterprise-field--full">
                <label class="enterprise-field-label">Contracts</label>
                <?php if ($region && (int) $siteTotal > count($sites)): ?>
                    <div class="form-text mb-2">Showing <?= count($sites) ?> of <?= (int) $siteTotal ?> in <?= esc($region) ?>.</div>
                <?php elseif (($siteTotal ?? count($sites)) > count($sites)): ?>
                    <div class="form-text mb-2">Showing <?= count($sites) ?> of <?= (int) ($siteTotal ?? count($sites)) ?> configured contracts.</div>
                <?php endif; ?>
                <select name="contract_ids[]" class="form-select" multiple size="<?= min(10, max(4, count($sites))) ?>" id="ai-plan-contracts">
                    <?php foreach ($sites as $site): ?>
                        <?php $cid = (int) $site['contract_id']; ?>
                        <option value="<?= $cid ?>"
                            <?= in_array($cid, $selectedIds ?? [], true) ? 'selected' : '' ?>>
                            <?= esc(($site['contract_number'] ? $site['contract_number'] . ' — ' : '') . $site['contract_title']) ?>
                            (<?= esc($site['location_city'] ?? $site['location_name']) ?>: <?= esc($site['location_name']) ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="form-text">
                    <?php if ($region): ?>
                        Contracts in <strong><?= esc($region) ?></strong> are pre-selected up to the batch size.
                        Change selection manually if needed — only the first <?= (int) ($batchLimit ?? 40) ?> are planned.
                    <?php else: ?>
                        Choose a region above, or manually select contracts (large catalogues require a region or batch cap).
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="enterprise-settings-card__footer">
            <a href="<?= base_url('transport/ai/plans') ?>" class="btn btn-outline-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">
                <i class="fa-solid fa-wand-magic-sparkles me-1"></i> Generate Plan
            </button>
        </div>
    </form>
</article>

<script>
(function () {
    const scopeForm = document.getElementById('ai-plan-scope-form');
    const regionSelect = document.getElementById('ai-plan-region');
    const contractSelect = document.getElementById('ai-plan-contracts');

    function selectedBatchLimit() {
        const checked = scopeForm?.querySelector('input[name="batch_limit"]:checked');
        return checked ? parseInt(checked.value, 10) : 40;
    }

    function autoSelectContracts() {
        if (!contractSelect) return;
        const limit = selectedBatchLimit();
        Array.from(contractSelect.options).forEach((opt, idx) => {
            opt.selected = idx < limit;
        });
    }

    regionSelect?.addEventListener('change', () => scopeForm?.submit());
    scopeForm?.querySelectorAll('input[name="batch_limit"]').forEach((radio) => {
        radio.addEventListener('change', () => {
            autoSelectContracts();
            const hidden = document.querySelector('#ai-plan-generate-form input[name="batch_limit"]');
            if (hidden) hidden.value = String(selectedBatchLimit());
        });
    });
})();
</script>

<article class="enterprise-settings-card mt-4" style="max-width:860px;">
    <div class="enterprise-settings-card__head">
        <i class="fa-solid fa-circle-info"></i>
        <h2 class="enterprise-settings-card__title">What the AI does</h2>
    </div>
    <ul class="text-muted small mb-0">
        <li>Takes each contract site, the staff assigned on that contract, and their shift timing (or the site default shift).</li>
        <li>Splits staff into vehicle-sized groups and plans a direct garage/depot → site run timed to arrive before shift start.</li>
        <li>Assigns the best available driver per route — checking licenses, availability, overlaps and daily working-hour limits.</li>
        <li>Estimates distance, travel time, fuel consumption and transportation cost per route.</li>
        <li>Flags every conflict it cannot resolve and recommends replacement drivers or vehicles.</li>
        <li>Publishes nothing: the plan becomes official only after manager approval.</li>
    </ul>
</article>

<?= $this->endSection() ?>
