<?php
// Resources/views/pages/lead-form.php

// Determine mode + target URLs
$isEdit = !empty($lead) && !empty($lead['id']);
$title  = $isEdit ? 'Edit Lead' : 'New Lead';

// Pull any old form data (from validation failure)
$formData = $_SESSION['form_data'] ?? [];
unset($_SESSION['form_data']);

// Helper to get value: old form data > lead > default
$val = function ($key, $default = '') use ($formData, $lead) {
    if (isset($formData[$key])) {
        return $formData[$key];
    }
    if (!empty($lead) && isset($lead[$key])) {
        return $lead[$key];
    }
    return $default;
};

$action = $isEdit
    ? "/lead-management/public/app/leads/" . (int)$lead['id'] . "/update"
    : "/lead-management/public/app/leads/store";

$statusCurrent = $val('status', $isEdit ? ($lead['status'] ?? 'new') : 'new');
$sourceCurrent = $val('source', $isEdit ? ($lead['source'] ?? 'manual') : 'manual');
?>
<div class="dashboard-container">
    <!-- Header -->
    <header class="dashboard-header">
        <div class="header-content">
            <div class="welcome-section">
                <h1><?= htmlspecialchars($title) ?></h1>
                <p>
                    <?= $isEdit
                        ? 'Update lead details, status, and notes.'
                        : 'Create a new lead and optionally score with AI.' ?>
                </p>
            </div>
            <div class="header-actions">
                <a href="/lead-management/public/app/leads"
                    style="margin-right:.5rem; text-decoration:none; font-size:.85rem; color:var(--sky-700);">
                    <i class="fas fa-arrow-left"></i> Back to Leads
                </a>
            </div>
        </div>
    </header>

    <!-- Form Card -->
    <section class="tasks-section" style="margin-top:1.5rem;">
        <!-- Flash messages -->
        <?php if (!empty($_SESSION['error'])): ?>
            <div class="flash-error">
                <?= $_SESSION['error'];
                unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>
        <?php if (!empty($_SESSION['success'])): ?>
            <div class="flash-success">
                <?= $_SESSION['success'];
                unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>

        <div class="section-header">
            <h2><i class="fas fa-id-card"></i> Lead Details</h2>
        </div>

        <form action="<?= htmlspecialchars($action) ?>" method="POST" class="lead-form">
            <!-- Row 1: Name -->
            <div class="form-row">
                <div class="form-field">
                    <label for="first_name">
                        First Name <span class="required">*</span>
                    </label>
                    <input
                        type="text"
                        id="first_name"
                        name="first_name"
                        required
                        value="<?= htmlspecialchars($val('first_name')) ?>"
                        placeholder="Alex">
                </div>
                <div class="form-field">
                    <label for="last_name">
                        Last Name
                    </label>
                    <input
                        type="text"
                        id="last_name"
                        name="last_name"
                        value="<?= htmlspecialchars($val('last_name')) ?>"
                        placeholder="Smith">
                </div>
            </div>

            <!-- Row 2: Contact -->
            <div class="form-row">
                <div class="form-field">
                    <label for="email">
                        Email
                    </label>
                    <input
                        type="email"
                        id="email"
                        name="email"
                        value="<?= htmlspecialchars($val('email')) ?>"
                        placeholder="alex@example.com">
                    <small class="field-hint">
                        Used for AI email drafts and follow-ups.
                    </small>
                </div>
                <div class="form-field">
                    <label for="phone">
                        Phone
                    </label>
                    <input
                        type="text"
                        id="phone"
                        name="phone"
                        value="<?= htmlspecialchars($val('phone')) ?>"
                        placeholder="+1 (555) 000-0000">
                </div>
            </div>

            <!-- Row 3: Company -->
            <div class="form-row">
                <div class="form-field">
                    <label for="company">
                        Company
                    </label>
                    <input
                        type="text"
                        id="company"
                        name="company"
                        value="<?= htmlspecialchars($val('company')) ?>"
                        placeholder="Acme Inc.">
                </div>
                <div class="form-field">
                    <label for="industry">
                        Industry
                    </label>
                    <input
                        type="text"
                        id="industry"
                        name="industry"
                        value="<?= htmlspecialchars($val('industry')) ?>"
                        placeholder="SaaS, Fintech, Real Estate...">
                </div>
            </div>

            <!-- Row 4: Source + Status -->
            <div class="form-row">
                <div class="form-field">
                    <label for="source">
                        Source
                    </label>
                    <select id="source" name="source">
                        <?php
                        $sources = [
                            'manual'   => 'Manual entry',
                            'form'     => 'Form submission',
                            'website'  => 'Website',
                            'referral' => 'Referral',
                            'ad'       => 'Paid Ads',
                            'other'    => 'Other',
                        ];
                        foreach ($sources as $value => $label): ?>
                            <option value="<?= htmlspecialchars($value) ?>"
                                <?= $sourceCurrent === $value ? 'selected' : '' ?>>
                                <?= htmlspecialchars($label) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-field">
                    <label for="status">
                        Status
                    </label>
                    <select id="status" name="status">
                        <?php
                        $statuses = [
                            'new'       => 'New',
                            'active'    => 'Active / In Progress',
                            'converted' => 'Converted',
                            'lost'      => 'Lost',
                        ];
                        foreach ($statuses as $value => $label): ?>
                            <option value="<?= htmlspecialchars($value) ?>"
                                <?= $statusCurrent === $value ? 'selected' : '' ?>>
                                <?= htmlspecialchars($label) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- Row 5: Notes -->
            <div class="form-row">
                <div class="form-field" style="grid-column: 1 / -1;">
                    <label for="notes">
                        Internal Notes
                    </label>
                    <textarea
                        id="notes"
                        name="notes"
                        rows="4"
                        placeholder="Context, call notes, objections, or anything that helps AI and your team."><?= htmlspecialchars($val('notes')) ?></textarea>
                </div>
            </div>

            <!-- Auto-score (only on create) -->
            <?php if (!$isEdit): ?>
                <div class="form-row">
                    <div class="form-field" style="grid-column: 1 / -1;">
                        <label class="checkbox-label">
                            <input
                                type="checkbox"
                                name="auto_score"
                                value="1"
                                <?= !empty($formData['auto_score']) ? 'checked' : '' ?>>
                            <span>Auto-score this lead with AI after saving</span>
                        </label>
                        <small class="field-hint">
                            Uses your configured AI provider to score and categorize the lead immediately.
                        </small>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Actions -->
            <div class="form-actions">
                <button type="submit" class="btn-primary">
                    <i class="fas fa-save"></i>
                    <?= $isEdit ? 'Save changes' : 'Create lead' ?>
                </button>

                <?php if ($isEdit): ?>
                    <a href="/lead-management/public/app/leads/<?= (int)$lead['id'] ?>"
                        class="btn-secondary">
                        Cancel
                    </a>
                <?php else: ?>
                    <a href="/lead-management/public/app/leads"
                        class="btn-secondary">
                        Cancel
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </section>
</div>

<style>
    /* Reuse SkyBlue conventions */

    .lead-form {
        display: flex;
        flex-direction: column;
        gap: 1.25rem;
    }

    .form-row {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 1.25rem;
    }

    @media (max-width: 768px) {
        .form-row {
            grid-template-columns: 1fr;
        }
    }

    .form-field {
        display: flex;
        flex-direction: column;
        gap: .35rem;
    }

    .form-field label {
        font-size: .9rem;
        font-weight: 600;
        color: var(--sky-800);
    }

    .form-field input[type="text"],
    .form-field input[type="email"],
    .form-field select,
    .form-field textarea {
        border-radius: 10px;
        border: 1px solid var(--sky-200);
        padding: .6rem .8rem;
        font-size: .9rem;
        background: #fff;
        transition: var(--transition);
    }

    .form-field input:focus,
    .form-field select:focus,
    .form-field textarea:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.15);
    }

    .required {
        color: var(--danger);
        margin-left: 2px;
    }

    .field-hint {
        font-size: .75rem;
        color: var(--sky-600);
    }

    .checkbox-label {
        display: inline-flex;
        align-items: center;
        gap: .5rem;
        font-size: .9rem;
        color: var(--sky-800);
    }

    .checkbox-label input[type="checkbox"] {
        width: 16px;
        height: 16px;
    }

    .form-actions {
        margin-top: .75rem;
        display: flex;
        gap: .75rem;
        align-items: center;
    }

    .btn-primary {
        display: inline-flex;
        align-items: center;
        gap: .4rem;
        background: var(--primary);
        color: #fff;
        border-radius: var(--radius);
        padding: .6rem 1.3rem;
        border: none;
        font-size: .9rem;
        font-weight: 600;
        cursor: pointer;
        text-decoration: none;
        box-shadow: 0 8px 20px rgba(59, 130, 246, 0.25);
        transition: var(--transition);
    }

    .btn-primary:hover {
        background: var(--primary-dark);
        transform: translateY(-1px);
        box-shadow: 0 12px 26px rgba(37, 99, 235, 0.35);
    }

    .btn-secondary {
        display: inline-flex;
        align-items: center;
        gap: .4rem;
        background: rgba(148, 163, 184, 0.1);
        color: var(--sky-700);
        border-radius: var(--radius);
        padding: .55rem 1.1rem;
        border: 1px solid var(--sky-200);
        font-size: .85rem;
        font-weight: 500;
        text-decoration: none;
        cursor: pointer;
        transition: var(--transition);
    }

    .btn-secondary:hover {
        background: rgba(148, 163, 184, 0.18);
    }

    /* Flash messages */
    .flash-error,
    .flash-success {
        border-radius: 10px;
        padding: .75rem .9rem;
        font-size: .85rem;
        margin-bottom: 1rem;
    }

    .flash-error {
        background: rgba(239, 68, 68, 0.08);
        border: 1px solid rgba(239, 68, 68, 0.3);
        color: var(--danger);
    }

    .flash-success {
        background: rgba(16, 185, 129, 0.08);
        border: 1px solid rgba(16, 185, 129, 0.3);
        color: var(--success);
    }
</style>