<?php
session_start();
if (!isset($_SESSION['agent_id'])) { header("Location: login.php"); exit; }
require_once '../config/db.php';
$agent_id   = $_SESSION['agent_id'];
$agent_name = $_SESSION['agent_name'];

// Handle add lead redirect before header
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_lead'])) {
    $phone   = trim($_POST['phone']);
    $name    = trim($_POST['name']??'');
    $email   = trim($_POST['email']??'');
    $ptype   = trim($_POST['project_type']??'');
    $notes   = trim($_POST['notes']??'');
    $src_id  = !empty($_POST['source_id'])  ? (int)$_POST['source_id']  : null;
    $stat_id = !empty($_POST['status_id'])  ? (int)$_POST['status_id']  : null;
    $b_name  = trim($_POST['building_name']??'');
    $area    = trim($_POST['area']??'');
    $city    = trim($_POST['city']??'');
    $dist    = trim($_POST['district']??'');
    $pin     = trim($_POST['pincode']??'');
    $state   = trim($_POST['state']??'');

    if (!empty($phone)) {
        $pdo->prepare("INSERT INTO leads (phone,name,email,project_type,notes,source_id,status_id,assigned_agent_id,is_junk,building_name,area,city,district,pincode,state) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$phone,$name,$email,$ptype,$notes,$src_id,$stat_id,$agent_id, 0,$b_name,$area,$city,$dist,$pin,$state]);
        $new_id = $pdo->lastInsertId();
        header("Location: lead_view.php?id=$new_id&msg=lead_added"); exit;
    } else {
        $save_error = "Phone number is required.";
    }
}

require_once 'includes/header.php';
?>
<!-- International Phone Input CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/css/intlTelInput.css">
<style>
    .iti { width: 100%; }
    .ag-card input[type="tel"] { width: 100% !important; }
</style>
<?php

if (isset($save_error)) echo "<div class='alert-error'><i class='fa-solid fa-circle-exclamation'></i> ".htmlspecialchars($save_error)."</div>";

$all_sources  = $pdo->query("SELECT * FROM lead_sources  ORDER BY name")->fetchAll();
$all_statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY name")->fetchAll();
$all_services = $pdo->query("SELECT * FROM lead_services WHERE status='active' ORDER BY name")->fetchAll();
?>
<script>document.getElementById('page-title').textContent='Add New Lead';</script>

<div style="max-width:620px;">
    <a href="my_leads.php" style="display:inline-flex;align-items:center;gap:6px;color:#64748b;text-decoration:none;font-weight:700;font-size:0.88rem;background:#f1f5f9;padding:9px 14px;border-radius:8px;margin-bottom:20px;">
        <i class="fa-solid fa-arrow-left"></i> Back to My Leads
    </a>

    <div class="ag-card" style="max-width: 800px;">
        <h3 class="ag-card-title"><i class="fa-solid fa-user-plus" style="color:var(--primary);margin-right:8px;"></i>Create New Lead</h3>
        <form method="POST">
            <h4 style="margin-bottom:15px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px; font-size: 0.9rem; text-transform: uppercase; font-weight: 800;">
                <i class="fa-solid fa-address-card"></i> Contact Information
            </h4>
            <div class="form-grid" style="margin-bottom: 25px;">
                <div>
                    <label>Full Name *</label>
                    <input type="text" name="name" placeholder="Lead's name" required>
                </div>
                <div>
                    <label>Phone Number *</label>
                    <input type="tel" name="phone" id="phone" placeholder="9XXXXXXXXX" required autofocus>
                </div>
                <div>
                    <label>Email Address</label>
                    <input type="email" name="email" placeholder="email@example.com">
                </div>
                <div>
                    <label>Project Type</label>
                    <select name="project_type">
                        <option value="">— Select Service/Type</option>
                        <?php foreach($all_services as $srv): ?>
                        <option value="<?=htmlspecialchars($srv['name'])?>"><?=htmlspecialchars($srv['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <h4 style="margin-bottom:15px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px; font-size: 0.9rem; text-transform: uppercase; font-weight: 800;">
                <i class="fa-solid fa-location-dot"></i> Address Details
            </h4>
            <div class="form-grid" style="margin-bottom: 25px;">
                <div>
                    <label>Building / Door No</label>
                    <input type="text" name="building_name" placeholder="e.g. #12, Door No">
                </div>
                <div>
                    <label>Area / Street</label>
                    <input type="text" name="area" placeholder="e.g. 3rd Cross">
                </div>
                <div>
                    <label>City</label>
                    <input type="text" name="city" placeholder="e.g. Krishnagiri">
                </div>
                <div>
                    <label>District</label>
                    <input type="text" name="district" placeholder="District name">
                </div>
                <div>
                    <label>Pincode</label>
                    <input type="text" name="pincode" placeholder="6XXXXX">
                </div>
                <div>
                    <label>State</label>
                    <input type="text" name="state" value="Tamil Nadu">
                </div>
            </div>

            <h4 style="margin-bottom:15px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px; font-size: 0.9rem; text-transform: uppercase; font-weight: 800;">
                <i class="fa-solid fa-diagram-project"></i> Pipeline Information
            </h4>
            <div class="form-grid" style="margin-bottom: 25px;">
                <div>
                    <label>Lead Source</label>
                    <select name="source_id">
                        <option value="">— Select Source</option>
                        <?php foreach($all_sources as $s): ?>
                        <option value="<?=$s['id']?>"><?=htmlspecialchars($s['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Pipeline Stage</label>
                    <select name="status_id">
                        <option value="">— Select Stage</option>
                        <?php foreach($all_statuses as $s): ?>
                        <option value="<?=$s['id']?>"><?=htmlspecialchars($s['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <h4 style="margin-bottom:15px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px; font-size: 0.9rem; text-transform: uppercase; font-weight: 800;">
                <i class="fa-solid fa-note-sticky"></i> Internal Notes
            </h4>
            <div style="margin-bottom: 25px;">
                <textarea name="notes" rows="4" placeholder="Add any specific requirements or call discussion notes here..."></textarea>
            </div>

            <div style="display: flex; gap: 12px;">
                <button type="submit" name="add_lead" class="btn-primary" style="flex: 1; justify-content:center; padding:15px; font-size:1rem; border-radius: 12px;">
                    <i class="fa-solid fa-save"></i> Save Lead Information
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>

<!-- International Phone Input JS -->
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/intlTelInput.min.js"></script>
<script>
    const phoneInput = document.querySelector("#phone");
    const iti = window.intlTelInput(phoneInput, {
        initialCountry: "in",
        separateDialCode: true,
        utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/utils.js",
    });
</script>
