<?php
// All redirect-based handlers BEFORE header
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'];

if (!isset($_GET['id'])) { header("Location: my_leads.php"); exit; }
$lead_id = (int)$_GET['id'];

// Update Lead Stage
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['change_stage_id'])) {
    $pdo->prepare("UPDATE leads SET status_id=? WHERE id=? AND assigned_agent_id=?")->execute([(int)$_POST['change_stage_id'], $lead_id, $agent_id]);
    header("Location: lead_view.php?id=$lead_id&msg=stage_updated"); exit;
}

// Success message mapping
$msg_map = [
    'stage_updated' => 'Lead stage updated successfully.',
    'lead_updated' => 'Lead details saved.',
    'fup_done' => 'Follow-up marked as completed.',
    'fup_added' => 'New follow-up scheduled.',
    'fup_updated' => 'Follow-up cancelled.',
    'meeting_scheduled' => 'Meeting confirmed successfully.',
];
if (isset($_GET['msg']) && isset($msg_map[$_GET['msg']])) {
    $success = $msg_map[$_GET['msg']];
}
if (isset($_GET['error'])) {
    $error = htmlspecialchars($_GET['error']);
}
// Update lead info (only on POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_lead'])) {
    $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']??'');
    $pdo->prepare("UPDATE leads SET name=?,email=?,building_name=?,area=?,city=?,district=?,pincode=?,state=?,project_type=?,notes=? WHERE id=? AND assigned_agent_id=?")
        ->execute([trim($_POST['name']??''), trim($_POST['email']??''), $b_name, $area, $city, $dist, $pin, $state, trim($_POST['project_type']??''), trim($_POST['notes']??''), $lead_id, $agent_id]);
    header("Location: lead_view.php?id=$lead_id&msg=lead_updated"); exit;
}
// Mark follow-up done with outcome (redirects)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_followup'])) {
    $f_id = (int)$_POST['complete_followup_id'];
    $result_notes  = trim($_POST['result_notes']);
    $new_status_id = !empty($_POST['new_status_id']) ? (int)$_POST['new_status_id'] : null;
    $next_date  = trim($_POST['next_date']  ?? '');
    // next_time and next_notes handled if date is set
    $next_notes = trim($_POST['next_notes'] ?? '');
    
    try {
        $pdo->beginTransaction();
        // Update current follow-up
        $pdo->prepare("UPDATE lead_followups SET status='completed', completed_at=NOW(), notes=CONCAT(COALESCE(notes,''),'\n\n**Outcome:**\n',?) WHERE id=?")
            ->execute([$result_notes, $f_id]);
        
        // Update lead status if requested
        if ($new_status_id) {
            $pdo->prepare("UPDATE leads SET status_id = ? WHERE id = ? AND assigned_agent_id = ?")->execute([$new_status_id, $lead_id, $agent_id]);
        }
        
        // Schedule next follow-up if requested
        if (!empty($next_date) && !empty($next_notes)) {
            $next_time = $_POST['next_time'] ?: '10:00';
            $pdo->prepare("INSERT INTO lead_followups (lead_id, followup_date, notes, status) VALUES (?, ?, ?, 'pending')")
                ->execute([$lead_id, $next_date . ' ' . $next_time . ':00', $next_notes]);
        }
        
        $pdo->commit();
        header("Location: lead_view.php?id=$lead_id&msg=fup_done"); exit;
    } catch (PDOException $e) { 
        $pdo->rollBack(); 
        header("Location: lead_view.php?id=$lead_id&error=" . urlencode($e->getMessage())); exit;
    }
}

// Cancel Follow-up (GET)
if (isset($_GET['f_action']) && $_GET['f_action'] === 'cancelled' && isset($_GET['f_id'])) {
    $f_id = (int)$_GET['f_id'];
    $pdo->prepare("UPDATE lead_followups SET status='cancelled' WHERE id=?")->execute([$f_id]);
    header("Location: lead_view.php?id=$lead_id&msg=fup_updated"); exit;
}

// Add new follow-up (redirects)
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_fup'])) {
    $f_date = trim($_POST['fup_date']);
    $f_notes = trim($_POST['fup_notes']);
    if (!empty($f_date)) {
        $pdo->prepare("INSERT INTO lead_followups (lead_id, followup_date, notes, status) VALUES (?, ?, ?, 'pending')")
            ->execute([$lead_id, $f_date, $f_notes]);
        header("Location: lead_view.php?id=$lead_id&msg=fup_added"); exit;
    }
}

// Quick Meeting Schedule (redirects)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quick_meeting'])) {
    $m_title    = trim($_POST['m_title']);
    $m_date     = trim($_POST['m_date']);
    $m_start    = trim($_POST['m_start']);
    $m_end      = trim($_POST['m_end']);
    $m_type     = trim($_POST['m_type'] ?? 'live_meeting');
    $m_link     = ($m_type === 'online_meeting') ? trim($_POST['m_link'] ?? '') : '';
    $m_location = trim($_POST['m_location'] ?? '');
    $m_notes    = trim($_POST['m_notes'] ?? '');
    if (!empty($m_title) && !empty($m_date) && !empty($m_start) && !empty($m_end)) {
        try {
            $pdo->prepare("INSERT INTO meetings (lead_id, agent_id, title, meeting_date, start_time, end_time, meeting_type, meeting_link, location, status, notes) VALUES (?,?,?,?,?,?,?,?,?,'scheduled',?)")
                ->execute([$lead_id, $agent_id, $m_title, $m_date, $m_start, $m_end, $m_type, $m_link, $m_location, $m_notes]);
            header("Location: lead_view.php?id=$lead_id&msg=meeting_scheduled"); exit;
        } catch (PDOException $e) { 
            header("Location: lead_view.php?id=$lead_id&error=" . urlencode($e->getMessage())); exit;
        }
    } else { 
        header("Location: lead_view.php?id=$lead_id&error=" . urlencode("Title, Date and Times are required.")); exit;
    }
}

// Convert to Customer (redirects)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['convert_to_customer'])) {
    $c_name      = trim($_POST['c_name']);
    $c_phone     = trim($_POST['c_phone']);
    $c_email     = trim($_POST['c_email']);
    $c_bname     = trim($_POST['c_building_name']);
    $c_area      = trim($_POST['c_area']);
    $c_city      = trim($_POST['c_city']);
    $c_district  = trim($_POST['c_district']);
    $c_pincode   = trim($_POST['c_pincode']);
    $c_state     = trim($_POST['c_state']);
    $c_project   = trim($_POST['c_project_type']);
    $c_notes     = trim($_POST['c_notes']);
    $c_status_id = !empty($_POST['c_status_id']) ? (int)$_POST['c_status_id'] : null;
    try {
        $pdo->beginTransaction();
        $pdo->prepare("INSERT INTO customers (lead_id, agent_id, name, phone, email, building_name, area, city, district, pincode, state, project_type, notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$lead_id, $agent_id, $c_name, $c_phone, $c_email, $c_bname, $c_area, $c_city, $c_district, $c_pincode, $c_state, $c_project, $c_notes]);
        if ($c_status_id) {
            $pdo->prepare("UPDATE leads SET status_id = ? WHERE id = ? AND assigned_agent_id = ?")->execute([$c_status_id, $lead_id, $agent_id]);
        }
        $pdo->commit();
        header("Location: customers.php?msg=converted"); exit;
    } catch (PDOException $e) { 
        $pdo->rollBack(); 
        header("Location: lead_view.php?id=$lead_id&error=" . urlencode($e->getMessage())); exit;
    }
}

// Security — agent can only view their assigned leads
$lead = $pdo->prepare("SELECT l.*, st.name as status_name, st.color_code, s.name as source_name
    FROM leads l
    LEFT JOIN lead_statuses st ON l.status_id = st.id
    LEFT JOIN lead_sources s ON l.source_id = s.id
    WHERE l.id = ? AND l.assigned_agent_id = ?");
$lead->execute([$lead_id, $agent_id]);
$lead = $lead->fetch();
if (!$lead) { header("Location: my_leads.php"); exit; }

require_once 'includes/header.php';

// Fetch all statuses for stage strip
$all_statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY id ASC")->fetchAll();
$all_services = $pdo->query("SELECT * FROM lead_services WHERE status='active' ORDER BY name ASC")->fetchAll();
$followups    = $pdo->prepare("SELECT * FROM lead_followups WHERE lead_id = ? ORDER BY followup_date DESC");
$followups->execute([$lead_id]);
$followups    = $followups->fetchAll();
$clean_phone = preg_replace('/[^0-9]/','',$lead['phone']);
?>
<style>
.timeline-container { display: flex; flex-direction: column; gap: 15px; margin-top:10px; }
.timeline-card { border-left: 4px solid var(--primary); padding:15px; margin-bottom:0 !important; }
.timeline-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; flex-wrap: wrap; gap: 8px; }
.timeline-time { font-size: 0.85rem; font-weight: 700; color: #475569; }
.timeline-notes { margin: 0; color: #334155; font-size: 0.88rem; line-height: 1.5; padding: 10px; background: #f8fafc; border-radius: 8px; border: 1px solid #f1f5f9; }
.badge-fixed { padding: 3px 8px; border-radius: 8px; font-size: 0.72rem; font-weight: 800; text-transform: uppercase; }

/* Modal specific */
.modal { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.6); z-index:9999; align-items:center; justify-content:center; padding:15px; }
.modal-content { background:#fff; border-radius:16px; padding:28px; width:100%; max-width:540px; max-height:90vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,0.3); }
</style>
<script>document.getElementById('page-title').textContent='Lead Details';</script>

<?php if(isset($success)): ?><div class="alert-success"><i class="fa-solid fa-circle-check"></i> <?=htmlspecialchars($success)?></div><?php endif; ?>
<?php if(isset($error)): ?><div class="alert-error"><i class="fa-solid fa-triangle-exclamation"></i> <?=htmlspecialchars($error)?></div><?php endif; ?>

<!-- Back + Header -->
<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;flex-wrap:wrap;">
    <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;">
        <i class="fa-solid fa-arrow-left"></i> Back
    </a>
    <h2 style="font-size:1.4rem;font-weight:800;color:#0f172a;"><?=htmlspecialchars($lead['phone'])?></h2>
    <?php if($lead['status_name']): ?>
        <span class="ag-badge" style="font-size:0.82rem;background:<?=htmlspecialchars($lead['color_code'])?>20;color:<?=htmlspecialchars($lead['color_code'])?>;border:1px solid <?=htmlspecialchars($lead['color_code'])?>40;padding:5px 12px;"><?=htmlspecialchars($lead['status_name'])?></span>
    <?php endif; ?>
    <a href="tel:<?=$clean_phone?>" style="padding:9px 14px;background:#0f172a;color:#fff;border-radius:8px;text-decoration:none;font-weight:700;font-size:0.85rem;display:inline-flex;align-items:center;gap:6px;"><i class="fa-solid fa-phone"></i> Call</a>
    <a href="https://wa.me/<?=$clean_phone?>" target="_blank" style="padding:9px 14px;background:#25D366;color:#fff;border-radius:8px;text-decoration:none;font-weight:700;font-size:0.85rem;display:inline-flex;align-items:center;gap:6px;"><i class="fa-brands fa-whatsapp"></i> WhatsApp</a>
    <button onclick="document.getElementById('meetingModal').style.display='flex'" style="padding:9px 14px; background:#3b82f6; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:0.85rem; display:inline-flex; align-items:center; gap:6px;"><i class="fa-solid fa-calendar-plus"></i> Meeting</button>
    <button onclick="document.getElementById('convertModal').style.display='flex'" style="padding:9px 14px; background:#22c55e; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:0.85rem; display:inline-flex; align-items:center; gap:6px;"><i class="fa-solid fa-user-plus"></i> Convert</button>
</div>

<!-- Lead Stage Strip -->
<div class="ag-card" style="padding:16px 22px;margin-bottom:18px;">
    <div style="font-size:0.72rem;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:0.06em;margin-bottom:10px;">Lead Stage</div>
    <div style="display:flex;flex-wrap:wrap;gap:8px;">
        <?php foreach($all_statuses as $s): $isActive=($lead['status_id']==$s['id']); ?>
        <form method="POST">
            <button type="submit" name="change_stage_id" value="<?=$s['id']?>" style="
                padding:6px 14px;border-radius:20px;font-size:0.8rem;font-weight:700;cursor:pointer;border:2px solid <?=htmlspecialchars($s['color_code'])?>;
                background:<?=$isActive?htmlspecialchars($s['color_code']):'transparent'?>;
                color:<?=$isActive?'#fff':htmlspecialchars($s['color_code'])?>;
                <?= $isActive ? 'box-shadow:0 4px 10px '.htmlspecialchars($s['color_code']).'40;' : '' ?>
            ">
                <?=$isActive?'✓ ':''?><?=htmlspecialchars($s['name'])?>
            </button>
        </form>
        <?php endforeach; ?>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">

    <!-- Lead Info -->
    <div class="ag-card">
        <h3 class="ag-card-title">Lead Information</h3>
        <form method="POST">
            <div class="form-grid">
                <div>
                    <label>Name</label>
                    <input type="text" name="name" value="<?=htmlspecialchars($lead['name']??'')?>">
                </div>
                <div>
                    <label>Phone</label>
                    <input type="text" value="<?=htmlspecialchars($lead['phone'])?>" readonly style="background:#f8fafc;cursor:not-allowed;">
                </div>
                <div>
                    <label>Email</label>
                    <input type="email" name="email" value="<?=htmlspecialchars($lead['email']??'')?>">
                </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'])?>" <?=($lead['project_type']==$srv['name']?'selected':'')?>><?=htmlspecialchars($srv['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Lead Source</label>
                    <input type="text" value="<?=htmlspecialchars($lead['source_name']??'Unknown/Direct')?>" readonly style="background:#f8fafc;cursor:not-allowed;">
                </div>
                <div>
                    <label>Added On</label>
                    <input type="text" value="<?=date('d M Y, h:i A', strtotime($lead['created_at']))?>" readonly style="background:#f8fafc;cursor:not-allowed;">
                </div>
                <div>
                    <label>Building / Door No</label>
                    <input type="text" name="building_name" value="<?=htmlspecialchars($lead['building_name']??'')?>">
                </div>
                <div>
                    <label>Area / Street</label>
                    <input type="text" name="area" value="<?=htmlspecialchars($lead['area']??'')?>">
                </div>
                <div>
                    <label>City</label>
                    <input type="text" name="city" value="<?=htmlspecialchars($lead['city']??'')?>">
                </div>
                <div>
                    <label>District</label>
                    <input type="text" name="district" value="<?=htmlspecialchars($lead['district']??'')?>">
                </div>
                <div>
                    <label>Pincode</label>
                    <input type="text" name="pincode" value="<?=htmlspecialchars($lead['pincode']??'')?>">
                </div>
                <div>
                    <label>State</label>
                    <input type="text" name="state" value="<?=htmlspecialchars($lead['state']??'Tamil Nadu')?>">
                </div>
                <div class="col-span-2">
                    <label>Notes</label>
                    <textarea name="notes" rows="3"><?=htmlspecialchars($lead['notes']??'')?></textarea>
                </div>
            </div>
            <button type="submit" name="update_lead" class="btn-primary" style="margin-top:14px;width:100%;justify-content:center;"><i class="fa-solid fa-floppy-disk"></i> Save Changes</button>
        </form>
    </div>

    <!-- Follow-ups -->
    <div>
        <!-- Add Follow-up -->
        <div class="ag-card" style="margin-bottom:16px;">
            <h3 class="ag-card-title">Schedule Follow-up</h3>
            <form method="POST">
                <div style="margin-bottom:12px;">
                    <label>Date & Time</label>
                    <input type="datetime-local" name="fup_date" value="<?=date('Y-m-d\TH:i')?>" required>
                </div>
                <div style="margin-bottom:12px;">
                    <label>Notes</label>
                    <textarea name="fup_notes" rows="2" placeholder="What's the plan for this follow-up?"></textarea>
                </div>
                <button type="submit" name="add_fup" class="btn-primary" style="width:100%;justify-content:center;"><i class="fa-solid fa-calendar-plus"></i> Schedule</button>
            </form>
        </div>

        <!-- Follow-up Timeline -->
        <h3 class="ag-card-title" style="border:none; margin-bottom:12px; padding-bottom:0;">Follow-up Timeline</h3>
        
        <?php if(empty($followups)): ?>
            <div class="ag-card" style="text-align:center; color:#94a3b8; padding: 40px 20px;">
                <i class="fa-regular fa-calendar-xmark" style="font-size: 2rem; color: #e2e8f0; margin-bottom: 10px; display: block;"></i>
                No follow-ups scheduled yet.
            </div>
        <?php else: ?>
            <div class="timeline-container">
                <?php 
                $now_ts = time();
                foreach($followups as $f): 
                    $f_ts = strtotime($f['followup_date']);
                    $is_done = ($f['status']==='completed');
                    $is_cancelled = ($f['status']==='cancelled');
                    $is_missed = (!$is_done && !$is_cancelled && $f_ts < $now_ts);
                ?>
                <div class="ag-card timeline-card" style="<?=$is_done?'opacity:0.75; border-left-color:#22c55e;':($is_cancelled?'opacity:0.6; border-left-color:#94a3b8;':($is_missed?'border-left-color:#ef4444;':''))?>">
                    <div class="timeline-header">
                        <div class="timeline-time">
                            <i class="fa-regular fa-calendar"></i> <?=date('M d, Y', $f_ts)?> 
                            <span style="color:#cbd5e1; margin:0 4px;">|</span>
                            <i class="fa-regular fa-clock"></i> <?=date('h:i A', $f_ts)?>
                        </div>
                        <div>
                            <?php if($is_done): ?>
                                <span class="badge-fixed" style="background:#dcfce7; color:#16a34a;">Done</span>
                            <?php elseif($is_cancelled): ?>
                                <span class="badge-fixed" style="background:#f1f5f9; color:#64748b;">Cancelled</span>
                            <?php elseif($is_missed): ?>
                                <span class="badge-fixed" style="background:#fee2e2; color:#ef4444;">Overdue</span>
                            <?php else: ?>
                                <span class="badge-fixed" style="background:#e0f2fe; color:#0ea5e9;">Upcoming</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="timeline-notes">
                        <?= nl2br(htmlspecialchars($f['notes'])) ?>
                    </div>

                    <?php if(!$is_done && !$is_cancelled): ?>
                        <div style="display:flex; gap:10px; margin-top:12px;">
                            <button type="button" onclick="openFupModal(<?=$f['id']?>)" class="btn-primary" style="flex:1; justify-content:center; background:#10b981; padding:8px; font-size:0.82rem;"><i class="fa-solid fa-check"></i> Mark Done</button>
                            <a href="lead_view.php?id=<?=$lead_id?>&f_action=cancelled&f_id=<?=$f['id']?>" class="btn-primary" style="flex:1; justify-content:center; background:#94a3b8; padding:8px; font-size:0.82rem;"><i class="fa-solid fa-ban"></i> Cancel</a>
                        </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Schedule Meeting Modal -->
<div id="meetingModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.6); z-index:9999; align-items:center; justify-content:center; padding:15px;">
    <div style="background:#fff; border-radius:16px; padding:28px; width:100%; max-width:560px; max-height:90vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:20px;">
            <h3 style="margin:0; color:var(--dark);"><i class="fa-solid fa-calendar-plus" style="color:#3b82f6; margin-right:8px;"></i>Schedule Meeting</h3>
            <button type="button" onclick="document.getElementById('meetingModal').style.display='none'" style="background:none; border:none; font-size:1.4rem; color:#94a3b8; cursor:pointer;">&#x2715;</button>
        </div>
        <form action="lead_view.php?id=<?= $lead_id ?>" method="POST">
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:16px;">
                <div style="grid-column:1/-1;">
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Meeting Title *</label>
                    <input type="text" name="m_title" value="Meeting - <?= htmlspecialchars($lead['phone']) ?>" required style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Date *</label>
                    <input type="date" name="m_date" value="<?= date('Y-m-d') ?>" required style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Start Time *</label>
                    <input type="time" name="m_start" value="10:00" required style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">End Time *</label>
                    <input type="time" name="m_end" value="11:00" required style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Meeting Type</label>
                    <select name="m_type" id="m_type_sel" onchange="toggleMLink()" style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; background:#fff; font-family:inherit;">
                        <option value="live_meeting">&#128309; Live Meeting</option>
                        <option value="site_visit">&#128993; Site Visit</option>
                        <option value="online_meeting">&#128995; Online Meeting</option>
                    </select>
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Location</label>
                    <input type="text" name="m_location" placeholder="Office / Site address" style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; font-family:inherit;">
                </div>
                <div id="m_link_row" style="grid-column:1/-1; display:none;">
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#8b5cf6;"><i class="fa-solid fa-video"></i> Online Meeting Link</label>
                    <input type="url" name="m_link" placeholder="https://zoom.us/j/..." style="width:100%; padding:10px 14px; border:2px solid #8b5cf6; border-radius:8px; font-family:inherit; background:#faf7ff;">
                </div>
                <div style="grid-column:1/-1;">
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Notes / Agenda</label>
                    <textarea name="m_notes" rows="2" placeholder="What will be discussed?" style="width:100%; padding:10px 14px; border:1px solid var(--border); border-radius:8px; font-family:inherit; resize:vertical;"></textarea>
                </div>
            </div>
            <div style="display:flex; gap:10px;">
                <button type="submit" name="quick_meeting" value="1" style="flex:1; padding:12px; background:#3b82f6; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:0.95rem;"><i class="fa-solid fa-calendar-check"></i> Confirm Meeting</button>
                <button type="button" onclick="document.getElementById('meetingModal').style.display='none'" style="padding:12px 20px; background:#f1f5f9; color:var(--dark); border:none; border-radius:8px; font-weight:600; cursor:pointer;">Cancel</button>
            </div>
        </form>
    </div>
</div>

<!-- Convert to Customer Modal -->
<div id="convertModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.6); z-index:9999; align-items:center; justify-content:center; padding:15px;">
    <div style="background:#fff; border-radius:16px; padding:30px; width:100%; max-width:520px; max-height:90vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,0.3);">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:20px;">
            <h3 style="margin:0; color:var(--dark);"><i class="fa-solid fa-user-plus" style="color:#22c55e; margin-right:8px;"></i> Convert to Customer</h3>
            <button onclick="document.getElementById('convertModal').style.display='none'" style="background:none; border:none; font-size:1.4rem; color:#94a3b8; cursor:pointer;">&#x2715;</button>
        </div>
        <form action="lead_view.php?id=<?= $lead_id ?>" method="POST">
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:15px;">
                <div style="grid-column:1/-1;">
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Full Name *</label>
                    <input type="text" name="c_name" value="<?= htmlspecialchars($lead['name']) ?>" required style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Phone *</label>
                    <input type="text" name="c_phone" value="<?= htmlspecialchars($lead['phone']) ?>" required style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Email</label>
                    <input type="email" name="c_email" value="<?= htmlspecialchars($lead['email'] ?? '') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Project Type</label>
                    <select name="c_project_type" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                        <option value="">— Select Service/Type</option>
                        <?php foreach($all_services as $srv): ?>
                        <option value="<?=htmlspecialchars($srv['name'])?>" <?=($lead['project_type']==$srv['name']?'selected':'')?>><?=htmlspecialchars($srv['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Update Lead Status</label>
                    <select name="c_status_id" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                        <option value="">-- Keep current --</option>
                        <?php foreach ($all_statuses as $s): ?>
                            <option value="<?= $s['id'] ?>" <?= ($s['name'] === 'Converted') ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Building / Door No</label>
                    <input type="text" name="c_building_name" value="<?= htmlspecialchars($lead['building_name'] ?? '') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Area / Street</label>
                    <input type="text" name="c_area" value="<?= htmlspecialchars($lead['area'] ?? '') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">City</label>
                    <input type="text" name="c_city" value="<?= htmlspecialchars($lead['city'] ?? '') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">District</label>
                    <input type="text" name="c_district" value="<?= htmlspecialchars($lead['district'] ?? '') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Pincode</label>
                    <input type="text" name="c_pincode" value="<?= htmlspecialchars($lead['pincode'] ?? '') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">State</label>
                    <input type="text" name="c_state" value="<?= htmlspecialchars($lead['state'] ?? 'Tamil Nadu') ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div style="grid-column:1/-1;">
                    <label style="display:block; margin-bottom:6px; font-weight:600; font-size:0.85rem; color:#64748b;">Notes</label>
                    <textarea name="c_notes" rows="2" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"><?= htmlspecialchars($lead['notes'] ?? '') ?></textarea>
                </div>
            </div>
            <div style="margin-top:20px; display:flex; gap:10px;">
                <button type="submit" name="convert_to_customer" value="1" style="flex:1; padding:12px; background:#22c55e; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:1rem;"><i class="fa-solid fa-user-plus"></i> Confirm Conversion</button>
                <button type="button" onclick="document.getElementById('convertModal').style.display='none'" style="padding:12px 20px; background:#f1f5f9; color:var(--dark); border:none; border-radius:8px; font-weight:600; cursor:pointer;">Cancel</button>
            </div>
        </form>
    </div>
</div>

<!-- Complete Follow-up Modal -->
<div id="completeFupModal" class="modal">
    <div class="modal-content">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:20px;">
            <h3 style="margin:0; color:var(--dark);"><i class="fa-solid fa-check-circle" style="color:#10b981; margin-right:8px;"></i>Complete Follow-up</h3>
            <button type="button" onclick="closeFupModal()" style="background:none; border:none; font-size:1.4rem; color:#94a3b8; cursor:pointer;">&#x2715;</button>
        </div>
        <form action="lead_view.php?id=<?= $lead_id ?>" method="POST">
            <input type="hidden" name="complete_followup_id" id="modal_fup_id">
            
            <div style="margin-bottom: 15px;">
                <label>Outcome / Discussion Notes *</label>
                <textarea name="result_notes" rows="3" required placeholder="What happened during this follow-up?"></textarea>
            </div>
            
            <div style="margin-bottom: 20px; padding-bottom:15px; border-bottom:1px dashed #e2e8f0;">
                <label>Update Lead Stage (Optional)</label>
                <select name="new_status_id">
                    <option value="">-- Keep Current Status (<?= htmlspecialchars($lead['status_name']) ?>) --</option>
                    <?php foreach($all_statuses as $st): ?>
                        <option value="<?= $st['id'] ?>" <?= $lead['status_id'] == $st['id'] ? 'selected' : '' ?>><?= htmlspecialchars($st['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <h4 style="margin: 0 0 12px 0; color:var(--primary); font-size:0.9rem; text-transform:uppercase; letter-spacing:0.04em;">Schedule Next Action</h4>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                <div>
                    <label>Next Date</label>
                    <input type="date" name="next_date">
                </div>
                <div>
                    <label>Next Time</label>
                    <input type="time" name="next_time" value="10:00">
                </div>
                <div style="grid-column: 1/-1;">
                    <label>Next Follow-up Notes</label>
                    <input type="text" name="next_notes" placeholder="Plan for the next step...">
                </div>
            </div>
            
            <div style="display:flex; gap:10px;">
                <button type="submit" name="complete_followup" value="1" style="flex:1; padding:12px; background:#10b981; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer;"><i class="fa-solid fa-check"></i> Save & Complete</button>
                <button type="button" onclick="closeFupModal()" style="padding:12px 20px; background:#f1f5f9; color:var(--dark); border:none; border-radius:8px; font-weight:600; cursor:pointer;">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
// Auto-hide messages
setTimeout(function() {
    const successMsg = document.querySelector('.alert-success');
    if (successMsg) {
        successMsg.style.transition = 'opacity 0.5s ease';
        successMsg.style.opacity = '0';
        setTimeout(() => successMsg.style.display = 'none', 500);
    }
}, 3000);

function toggleMLink() {
    const sel = document.getElementById('m_type_sel');
    const row = document.getElementById('m_link_row');
    row.style.display = (sel.value === 'online_meeting') ? 'block' : 'none';
}

function openFupModal(id) {
    document.getElementById('modal_fup_id').value = id;
    document.getElementById('completeFupModal').style.display = 'flex';
}
function closeFupModal() {
    document.getElementById('completeFupModal').style.display = 'none';
}
</script>

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