<?php

declare(strict_types=1);

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

HyroAdminAuth::requireLogin();

HyroCsrf::startSession();

$database = HyroDatabase::connection();

$currentAdminPage = 'leads';

$adminUser = HyroAdminAuth::user() ?? [];

$leadId = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$leadId || $leadId < 1) {
    http_response_code(404);
    exit('Lead not found.');
}

$leadStatement = $database->prepare(
    '
    SELECT
        id,
        lead_code,
        company_name,
        contact_name,
        product_code,
        status,
        assigned_to
    FROM hyro_leads
    WHERE id = :id
    LIMIT 1
    '
);

$leadStatement->execute([
    'id' => $leadId,
]);

$lead = $leadStatement->fetch();

if (!is_array($lead)) {
    http_response_code(404);
    exit('Lead not found.');
}

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

$errors = [];

$form = [
    'status' => (string) $lead['status'],
    'assigned_to' => (string) (
        $lead['assigned_to'] ?? ''
    ),
    'internal_note' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form = [
        'status' => strtolower(
            trim((string) ($_POST['status'] ?? ''))
        ),
        'assigned_to' => trim(
            (string) ($_POST['assigned_to'] ?? '')
        ),
        'internal_note' => trim(
            (string) ($_POST['internal_note'] ?? '')
        ),
    ];

    if (!HyroCsrf::verify($_POST['_token'] ?? null)) {
        $errors['general'] =
            'Your session expired. Refresh and try again.';
    } else {
        $activityRepository =
            new HyroLeadActivityRepository($database);

        $workflowService =
            new HyroLeadWorkflowService(
                $database,
                $activityRepository
            );

        $result = $workflowService->update(
            $leadId,
            $form,
            $adminUser
        );

        $errors = $result['errors'];

        if ($result['success']) {
            $_SESSION['hyro_lead_flash'] =
                'Lead updated successfully.';

            hyro_redirect(
                '/experience/admin/leads/view.php?id='
                . $leadId
            );
        }
    }
}

?>
<!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>
        Edit <?= hyro_escape($lead['lead_code']) ?>
        | 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>Edit Lead</h1>

                <p>
                    <?= hyro_escape($lead['lead_code']) ?>
                    ·
                    <?= hyro_escape($lead['company_name']) ?>
                </p>

            </div>

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

        </div>

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

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

                <h2>Lead Workflow</h2>

            </div>

            <div class="hyro-lead-edit-body">

                <?php if (isset($errors['general'])): ?>

                    <div class="hyro-admin-form-alert">
                        <?= hyro_escape(
                            $errors['general']
                        ) ?>
                    </div>

                <?php endif; ?>

                <form method="post" action="">

                    <?= HyroCsrf::input() ?>

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

                        <div class="hyro-admin-form-field">

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

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

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

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

                                <?php endforeach; ?>

                            </select>

                            <?php if (
                                isset($errors['status'])
                            ): ?>

                                <div class="hyro-admin-form-error">
                                    <?= hyro_escape(
                                        $errors['status']
                                    ) ?>
                                </div>

                            <?php endif; ?>

                        </div>

                        <div class="hyro-admin-form-field">

                            <label for="assigned_to">
                                Assigned To
                            </label>

                            <input
                                type="text"
                                id="assigned_to"
                                name="assigned_to"
                                value="<?= hyro_escape(
                                    $form['assigned_to']
                                ) ?>"
                                maxlength="100"
                                placeholder="Example: Shibu Founder"
                            >

                            <?php if (
                                isset($errors['assigned_to'])
                            ): ?>

                                <div class="hyro-admin-form-error">
                                    <?= hyro_escape(
                                        $errors['assigned_to']
                                    ) ?>
                                </div>

                            <?php endif; ?>

                        </div>

                        <div
                            class="hyro-admin-form-field full"
                        >

                            <label for="internal_note">
                                Internal Note
                            </label>

                            <textarea
                                id="internal_note"
                                name="internal_note"
                                maxlength="3000"
                                placeholder="Add follow-up details, customer discussion, next action or internal comments..."
                            ><?= hyro_escape(
                                $form['internal_note']
                            ) ?></textarea>

                            <?php if (
                                isset($errors['internal_note'])
                            ): ?>

                                <div class="hyro-admin-form-error">
                                    <?= hyro_escape(
                                        $errors['internal_note']
                                    ) ?>
                                </div>

                            <?php endif; ?>

                            <small>
                                This note is visible only inside
                                the HYRO ONE Admin Portal.
                            </small>

                        </div>

                    </div>

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

                        <button
                            type="submit"
                            class="hyro-admin-small-button primary"
                        >
                            Save Lead Changes
                        </button>

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

                    </div>

                </form>

            </div>

        </section>

    </main>

</div>

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

</body>
</html>