<?php
require_once 'config/db.php';

// === ALL redirect-based actions MUST be here, BEFORE header.php outputs anything ===

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

// Status/Stage Change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_stage_id'])) {
    try {
        $pdo->prepare("UPDATE leads SET status_id = ? WHERE id = ?")
            ->execute([(int)$_POST['change_stage_id'], $lead_id]);
        header("Location: lead_view.php?id=$lead_id&msg=stage_updated");
        exit;
    } catch (PDOException $e) { /* fall through */ }
}

// Assign Agent → redirects
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_agent'])) {
    $agent_val = $_POST['agent_id'] === '' ? null : (int)$_POST['agent_id'];
    try {
        $pdo->prepare("UPDATE leads SET assigned_agent_id = ? WHERE id = ?")->execute([$agent_val, $lead_id]);
        header("Location: lead_view.php?id=$lead_id&msg=agent_assigned");
        exit;
    } catch (PDOException $e) { /* fall through */ }
}

// Convert to Customer → redirects on success
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, name, phone, email, building_name, area, city, district, pincode, state, project_type, notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$lead_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 = ?")->execute([$c_status_id, $lead_id]);
        }
        $pdo->commit();
        header("Location: customers.php?msg=converted");
        exit;
    } catch (PDOException $e) {
        $pdo->rollBack();
        $conv_error = "Conversion error: " . $e->getMessage();
    }
}

// Follow-up Cancel (GET) → redirects
if (isset($_GET['f_action']) && isset($_GET['f_id']) && $_GET['f_action'] === 'cancelled') {
    try {
        $pdo->prepare("UPDATE lead_followups SET status = 'cancelled' WHERE id = ? AND lead_id = ?")
            ->execute([(int)$_GET['f_id'], $lead_id]);
        header("Location: lead_view.php?id=$lead_id&msg=f_updated");
        exit;
    } catch (PDOException $e) { /* fall through */ }
}

// === NOW it is safe to output HTML ===
require_once 'includes/header.php';

// Flash messages
$msg_map = [
    'f_updated'=>'Follow-up status updated.',
    'stage_updated'=>'Lead stage updated!',
    'agent_assigned'=>'Agent assigned successfully!'
];
if (isset($_GET['msg'])) $success = $msg_map[$_GET['msg']] ?? '';
if (isset($conv_error))  $error   = $conv_error;

// --- Non-redirect POST handlers (only set $success / $error) ---

// Add Follow-up
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_followup'])) {
    $date = trim($_POST['followup_date']);
    $time = trim($_POST['followup_time']);
    $notes = trim($_POST['notes']);
    if (!empty($date) && !empty($time) && !empty($notes)) {
        try {
            $pdo->prepare("INSERT INTO lead_followups (lead_id, followup_date, notes) VALUES (?, ?, ?)")
                ->execute([$lead_id, $date . ' ' . $time . ':00', $notes]);
            $success = "Follow-up scheduled successfully.";
        } catch (PDOException $e) { $error = "Database Error: " . $e->getMessage(); }
    } else {
        $error = "Date, Time, and Notes are required.";
    }
}

// Complete Follow-up with outcome + optional next step
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  = trim($_POST['next_time']  ?? '');
    $next_notes = trim($_POST['next_notes'] ?? '');
    try {
        $pdo->beginTransaction();
        $pdo->prepare("UPDATE lead_followups SET status='completed', notes=CONCAT(notes,'\n\n**Outcome:**\n',?) WHERE id=? AND lead_id=?")
            ->execute([$result_notes, $f_id, $lead_id]);
        if ($new_status_id) {
            $pdo->prepare("UPDATE leads SET status_id=? WHERE id=?")->execute([$new_status_id, $lead_id]);
        }
        if (!empty($next_date) && !empty($next_time) && !empty($next_notes)) {
            $pdo->prepare("INSERT INTO lead_followups (lead_id, followup_date, notes) VALUES (?,?,?)")
                ->execute([$lead_id, $next_date.' '.$next_time.':00', $next_notes]);
        }
        $pdo->commit();
        $success = "Follow-up marked as done.";
    } catch (PDOException $e) { $pdo->rollBack(); $error = "Error: " . $e->getMessage(); }
}

// Quick Meeting Schedule
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, title, meeting_date, start_time, end_time, meeting_type, meeting_link, location, status, notes) VALUES (?,?,?,?,?,?,?,?,'scheduled',?)")
                ->execute([$lead_id, $m_title, $m_date, $m_start, $m_end, $m_type, $m_link, $m_location, $m_notes]);
            $success = "Meeting scheduled successfully!";
        } catch (PDOException $e) { $error = "Meeting Error: " . $e->getMessage(); }
    } else {
        $error = "Title, Date and Times are required.";
    }
}



// Fetch Lead Details
$stmt = $pdo->prepare("
    SELECT l.*, 
           s.name as source_name, 
           st.name as status_name, st.color_code as status_color,
           f.name as funnel_name,
           stg.name as stage_name
    FROM leads l
    LEFT JOIN lead_sources s ON l.source_id = s.id
    LEFT JOIN lead_statuses st ON l.status_id = st.id
    LEFT JOIN lead_funnels f ON l.funnel_id = f.id
    LEFT JOIN lead_stages stg ON l.stage_id = stg.id
    WHERE l.id = ? AND l.is_junk = 0
");
$stmt->execute([$lead_id]);
$lead = $stmt->fetch();

if (!$lead) {
    echo "<div style='padding:40px; text-align:center;'><h3>Lead not found or moved to junk.</h3><a href='leads.php'>Back to Leads</a></div>";
    require_once 'includes/footer.php';
    exit;
}

// Format phone for apps
$clean_phone = preg_replace('/[^0-9]/', '', $lead['phone']);
if (strlen($clean_phone) == 10) {
    $clean_phone = '91' . $clean_phone;
}

// Fetch Follow-ups
$f_stmt = $pdo->prepare("SELECT * FROM lead_followups WHERE lead_id = ? ORDER BY followup_date ASC");
$f_stmt->execute([$lead_id]);
$f_stmt->execute([$lead_id]);
$followups = $f_stmt->fetchAll();

// Fetch Statuses for dropdowns
$all_statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY id ASC")->fetchAll();
$all_agents   = $pdo->query("SELECT * FROM sales_agents WHERE is_active=1 ORDER BY name ASC")->fetchAll();

?>

<div class="dashboard-content">
    <div class="lead-header-container">
        <h2 class="lead-title"><i class="fa-solid fa-address-card" style="color: var(--primary);"></i> <?= htmlspecialchars($lead['phone']) ?></h2>
        <div class="lead-header-actions">
            <a href="leads.php" class="btn-back"><i class="fa-solid fa-arrow-left"></i> Back</a>
            <a href="lead_add_edit.php?edit=<?= $lead_id ?>" class="btn-edit"><i class="fa-solid fa-pen" style="margin-right:8px;"></i> Edit Lead</a>
            <button onclick="document.getElementById('meetingModal').style.display='flex'" style="padding:10px 16px; background:#3b82f6; color:#fff; border:none; border-radius:8px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:8px;"><i class="fa-solid fa-calendar-plus"></i> Schedule Meeting</button>
            <button onclick="document.getElementById('convertModal').style.display='flex'" style="padding:10px 16px; background:#22c55e; color:#fff; border:none; border-radius:8px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:8px;"><i class="fa-solid fa-user-plus"></i> Convert to Customer</button>
        </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>
                        <input type="text" name="c_project_type" placeholder="e.g. House Construction" 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;">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>

    <?php if (isset($success)): ?>
        <div id="status-msg" class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div id="error-msg" class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="app-layout-grid">
        
        <!-- Left Column: Lead Info -->
        <div>
            <div class="app-card">
                <h3 class="app-card-title">Lead Profile</h3>
                
                <!-- Lead Stage quick-change strip -->
                <div style="margin-bottom:18px; padding-bottom:18px; border-bottom:1px solid #f1f5f9;">
                    <div style="font-size:0.78rem; 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:7px;">
                        <?php foreach ($all_statuses as $s): 
                            $isActive = ($s['id'] == $lead['status_id']);
                            $color = $s['color_code'] ?? '#64748b';
                        ?>
                        <form method="POST" action="lead_view.php?id=<?= $lead_id ?>">
                            <button type="submit" name="change_stage_id" value="<?= $s['id'] ?>"
                                style="display:inline-flex; align-items:center; gap:5px; padding:6px 13px; border-radius:10px; cursor:pointer; font-size:0.8rem; font-weight:700; transition:all 0.15s; position:relative; top:0;
                                background:<?= $isActive ? $color : '#f1f5f9' ?>;
                                color:<?= $isActive ? '#fff' : '#64748b' ?>;
                                border:2px solid <?= $isActive ? $color : '#e2e8f0' ?>;
                                box-shadow:<?= $isActive ? '0 3px 0 '.substr($color,0,7).'aa' : 'none' ?>;">
                                <?php if($isActive): ?><i class="fa-solid fa-circle-check"></i><?php endif; ?>
                                <?= htmlspecialchars($s['name']) ?>
                            </button>
                        </form>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="info-row">
                    <span class="info-label">Source</span>
                    <span class="info-value" style="color:#475569;"><?= htmlspecialchars($lead['source_name'] ?? 'Unknown/Direct') ?></span>
                </div>
                
                <?php if(!empty($lead['project_type'])): ?>
                <div class="info-row">
                    <span class="info-label">Project Type</span>
                    <span class="info-value" style="color:#475569;"><?= htmlspecialchars($lead['project_type']) ?></span>
                </div>
                <?php endif; ?>

                <div class="info-row">
                    <span class="info-label">Added On</span>
                    <span class="info-value" style="color:#475569;"><?= date('d M Y h:i A', strtotime($lead['created_at'])) ?></span>
                </div>

                <!-- Agent Assignment -->
                <?php
                $assigned_agent = null;
                if (!empty($lead['assigned_agent_id'])) {
                    foreach ($all_agents as $ag) {
                        if ($ag['id'] == $lead['assigned_agent_id']) { $assigned_agent = $ag; break; }
                    }
                    if (!$assigned_agent) {
                        // agent may be inactive — fetch directly
                        $tmp = $pdo->prepare("SELECT * FROM sales_agents WHERE id=?");
                        $tmp->execute([$lead['assigned_agent_id']]);
                        $assigned_agent = $tmp->fetch();
                    }
                }
                ?>
                <div style="padding-top:16px; border-top:1px solid #e2e8f0; margin-top:6px;">
                    <div style="font-size:0.78rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:0.06em; margin-bottom:10px;">Assigned Agent</div>
                    <?php if($assigned_agent): ?>
                        <div style="display:flex; align-items:center; justify-content:space-between; gap:8px; flex-wrap:wrap; margin-bottom:10px;">
                            <span style="display:inline-flex; align-items:center; gap:7px; background:#f0fdf4; color:#16a34a; padding:6px 13px; border-radius:14px; font-weight:700; font-size:0.88rem; border:1px solid #bbf7d0;">
                                <i class="fa-solid fa-user-tie"></i> <?= htmlspecialchars($assigned_agent['name']) ?>
                                <?php if(!empty($assigned_agent['phone'])): ?><span style="font-weight:400; color:#15803d; font-size:0.78rem;">· <?= htmlspecialchars($assigned_agent['phone']) ?></span><?php endif; ?>
                            </span>
                            <form method="POST" action="lead_view.php?id=<?= $lead_id ?>" style="display:inline;">
                                <input type="hidden" name="agent_id" value="">
                                <button type="submit" name="assign_agent" value="1" style="background:#fee2e2; color:#ef4444; border:1px solid #fecaca; border-radius:8px; padding:5px 12px; font-size:0.8rem; font-weight:700; cursor:pointer;">Unassign</button>
                            </form>
                        </div>
                    <?php endif; ?>
                    <?php if(count($all_agents) > 0): ?>
                    <form method="POST" action="lead_view.php?id=<?= $lead_id ?>" style="display:flex; gap:8px; align-items:center;">
                        <select name="agent_id" style="flex:1; padding:9px 12px; border-radius:8px; font-family:inherit; font-size:0.88rem;">
                            <option value=""><?= $assigned_agent ? '— Change Agent' : '— Select Agent' ?></option>
                            <?php foreach($all_agents as $ag): ?>
                                <option value="<?= $ag['id'] ?>" <?= ($assigned_agent && $assigned_agent['id'] == $ag['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($ag['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" name="assign_agent" value="1" style="padding:9px 15px; background:var(--primary); color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:0.88rem; white-space:nowrap;">
                            <i class="fa-solid fa-check"></i> Assign
                        </button>
                    </form>
                    <?php else: ?>
                        <a href="sales_agents.php" style="color:var(--primary); font-size:0.85rem;"><i class="fa-solid fa-plus" style="margin-right:4px;"></i>Create a Sales Agent first</a>
                    <?php endif; ?>
                </div>
            </div>

            <div class="app-card">
                <h3 class="app-card-title">Contact Details</h3>
                
                <div class="info-row" style="flex-direction: column; align-items: flex-start;">
                    <span class="info-label" style="margin-bottom:5px;">Phone</span>
                    <span style="font-weight:700; font-size:1.15rem; color:var(--dark);"><i class="fa-solid fa-phone" style="font-size: 0.9rem; color: var(--primary); margin-right: 5px;"></i> <?= htmlspecialchars($lead['phone']) ?></span>
                </div>
                
                <?php if(!empty($lead['email'])): ?>
                <div class="info-row" style="flex-direction: column; align-items: flex-start;">
                    <span class="info-label" style="margin-bottom:5px;">Email</span>
                    <span style="font-weight:600; font-size:1.1rem; color:var(--dark);"><i class="fa-solid fa-envelope" style="font-size: 0.9rem; color: var(--primary); margin-right: 5px;"></i> <?= htmlspecialchars($lead['email']) ?></span>
                </div>
                <?php endif; ?>
                
                <?php if(!empty($lead['city'])): ?>
                <div class="info-row" style="flex-direction: column; align-items: flex-start; border-bottom: none;">
                    <span class="info-label" style="margin-bottom:5px;">Address</span>
                    <span style="line-height:1.4; color:#334155; font-size:0.95rem;"><i class="fa-solid fa-location-dot" style="font-size: 0.9rem; color: var(--primary); margin-right: 5px;"></i> 
                        <?php 
                        $addr_parts = array_filter([$lead['building_name'], $lead['area'], $lead['city'], $lead['district'], $lead['pincode'], $lead['state']]);
                        echo htmlspecialchars(implode(', ', $addr_parts));
                        ?>
                    </span>
                </div>
                <?php endif; ?>

                <div style="display: flex; gap: 10px; flex-wrap: wrap; margin-top: 15px;">
                    <a href="tel:<?= htmlspecialchars($clean_phone) ?>" class="app-btn app-btn-dark"><i class="fa-solid fa-phone"></i> Call</a>
                    <a href="https://wa.me/<?= htmlspecialchars($clean_phone) ?>" target="_blank" class="app-btn app-btn-whatsapp"><i class="fa-brands fa-whatsapp"></i> Chat</a>
                </div>
            </div>

            <div class="app-card">
                <h3 class="app-card-title">Internal Notes</h3>
                <?php if(!empty($lead['notes'])): ?>
                    <div style="line-height: 1.6; color:#334155;">
                        <?= nl2br(htmlspecialchars($lead['notes'])) ?>
                    </div>
                <?php else: ?>
                    <p style="color:#94a3b8; font-style: italic;">No notes added for this lead.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Right Column: Follow-ups -->
        <div>
            <div class="app-card">
                <h3 class="app-card-title">Schedule Follow-up</h3>
                <form action="lead_view.php?id=<?= $lead_id ?>" method="POST">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                        <div>
                            <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Date*</label>
                            <input type="date" name="followup_date" required style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                        </div>
                        <div>
                            <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Time*</label>
                            <input type="time" name="followup_time" required  style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Follow-up Notes / Reason*</label>
                        <textarea name="notes" rows="2" required placeholder="e.g. Call to discuss quotation..." style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"></textarea>
                    </div>

                    <button type="submit" name="add_followup" style="width:100%; padding:12px; background:var(--primary); color:var(--white); border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-regular fa-calendar-check"></i> Add to Schedule</button>
                </form>
            </div>

            <h3 class="app-card-title" style="border:none; margin-bottom:15px; padding-bottom:0;">Follow-up Timeline</h3>
            
            <?php if(count($followups) > 0): ?>
                <div class="timeline-container">
                    <?php 
                    $current_time = time();
                    foreach ($followups as $f): 
                        $f_time = strtotime($f['followup_date']);
                        $is_past = $f['status'] === 'pending' && $f_time < $current_time;
                    ?>
                        <div class="app-card timeline-card">
                            
                            <!-- Status Indicator -->
                            <div class="timeline-header">
                                <strong style="color:var(--dark); font-size:1.05rem;">
                                    <i class="fa-regular fa-calendar" style="color:#64748b; margin-right:5px;"></i> <?= date('M d, Y', $f_time) ?> <span style="color:#94a3b8; font-weight:500; margin:0 5px;">|</span> <i class="fa-regular fa-clock" style="color:#64748b; margin-right:5px;"></i> <?= date('h:i A', $f_time) ?>
                                </strong>
                                <div class="timeline-badge-wrapper">
                                    <?php if($f['status'] === 'completed'): ?>
                                        <span class="badge badge-completed"><i class="fa-solid fa-check"></i> Done</span>
                                    <?php elseif($f['status'] === 'cancelled'): ?>
                                        <span class="badge badge-pending"><i class="fa-solid fa-xmark"></i> Cancelled</span>
                                    <?php elseif($is_past): ?>
                                        <span class="badge" style="background:#fee2e2; color:#ef4444;"><i class="fa-solid fa-triangle-exclamation"></i> Overdue</span>
                                    <?php else: ?>
                                        <span class="badge" style="background:#e0f2fe; color:var(--primary);"><i class="fa-regular fa-clock"></i> Upcoming</span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div style="margin-bottom: 10px;">
                                <p style="margin:0; color:#334155; font-size:0.95rem; line-height: 1.5; padding: 10px; background: #f8fafc; border-radius: 8px; border: 1px solid #f1f5f9;">
                                    <?= nl2br(htmlspecialchars($f['notes'])) ?>
                                </p>
                            </div>

                            <?php if($f['status'] === 'pending'): ?>
                                <div style="display: flex; gap: 10px; margin-top: 15px; flex-wrap: wrap;">
                                    <button type="button" onclick="openModal(<?= $f['id'] ?>)" class="app-btn app-btn-success" style="flex:1;"><i class="fa-solid fa-check" style="margin-right:5px;"></i> Mark Done</button>
                                    <a href="lead_view.php?id=<?= $lead_id ?>&f_action=cancelled&f_id=<?= $f['id'] ?>" class="app-btn app-btn-light" style="flex:1;"><i class="fa-solid fa-xmark" style="margin-right:5px;"></i> Cancel</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="app-card" style="text-align:center; color:#94a3b8; padding: 40px 20px;">
                    <i class="fa-regular fa-calendar-xmark" style="font-size: 2rem; color: #cbd5e1; margin-bottom: 10px; display: block;"></i>
                    No follow-ups scheduled for this lead.
                </div>
            <?php endif; ?>
        </div> <!-- End Right Column -->

    </div> <!-- End app-layout-grid -->
</div> <!-- End dashboard-content (Fixing unclosed tag) -->

<!-- Complete Follow-up Modal -->
<div id="completeModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; align-items:center; justify-content:center;">
    <div style="background:#fff; padding:30px; border-radius:12px; width:100%; max-width:500px; box-shadow:0 10px 25px rgba(0,0,0,0.1);">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; border-bottom:1px solid var(--border); padding-bottom:10px;">
            <h3 style="margin:0; color:var(--dark);">Complete/Update Follow-up</h3>
            <button onclick="closeModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:#94a3b8;">&times;</button>
        </div>
        
        <form action="lead_view.php?id=<?= $lead_id ?>" method="POST">
            <input type="hidden" name="complete_followup_id" id="modal_f_id" value="">
            
            <div style="margin-bottom: 15px;">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Notes / Outcome of this action*</label>
                <textarea name="result_notes" rows="3" required placeholder="What happened during this follow-up?" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"></textarea>
            </div>
            
            <div style="margin-bottom: 20px; padding-bottom:15px; border-bottom:1px dashed var(--border);">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Update Lead Status (Optional)</label>
                <select name="new_status_id" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#f8fafc;">
                    <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 15px 0; color:var(--primary); font-size:0.95rem;">Next Steps (Schedule Next Follow-up)</h4>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Next Date</label>
                    <input type="date" name="next_date" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Next Time</label>
                    <input type="time" name="next_time" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem;">Next Follow-up Reason (Required if date is set)</label>
                <input type="text" name="next_notes" placeholder="e.g. Call to discuss quotation..." style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
            </div>
            
            <div style="display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" onclick="closeModal()" style="padding:10px 20px; background:#e2e8f0; color:var(--dark); border:none; border-radius:6px; font-weight:600; cursor:pointer;">Cancel</button>
                <button type="submit" name="complete_followup" style="padding:10px 20px; background:#10b981; color:var(--white); border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-solid fa-check"></i> Save & Complete</button>
            </div>
        </form>
    </div>
</div>

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

function openModal(id) {
    document.getElementById('modal_f_id').value = id;
    document.getElementById('completeModal').style.display = 'flex';
}
function closeModal() {
    document.getElementById('completeModal').style.display = 'none';
}
// Validate next follow-up fields
document.querySelector('#completeModal form').addEventListener('submit', function(e) {
    const nextDate = this.querySelector('input[name="next_date"]').value;
    const nextNotes = this.querySelector('input[name="next_notes"]').value;
    
    if(nextDate && !nextNotes) {
        e.preventDefault();
        alert('Please provide a reason/note for the scheduled next follow-up.');
    }
});
</script>

<style>
.app-layout-grid {
    display: grid; 
    grid-template-columns: 1fr 1fr; 
    gap: 30px; 
    align-items: start;
}
.lead-header-container {
    display: flex; 
    justify-content: space-between; 
    align-items: center; 
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}
.lead-title {
    font-size: 1.8rem; 
    font-weight: 700; 
    color: var(--dark);
    margin: 0;
}
.lead-header-actions {
    display: flex;
    gap: 10px;
    align-items: center;
}
.btn-back {
    color: #64748b; 
    text-decoration: none; 
    font-weight: 600;
    padding: 10px 15px;
    border-radius: 8px;
    background: #f1f5f9;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.btn-edit {
    display: inline-flex; 
    align-items: center; 
    padding: 10px 20px; 
    background: #e0f2fe; 
    color: var(--primary); 
    border-radius: 8px; 
    text-decoration: none; 
    font-weight: 600;
}
.app-card {
    background: #fff; 
    padding: 20px; 
    border-radius: 12px; 
    border: 2px solid #cbd5e1; 
    box-shadow: 0 4px 6px rgba(0,0,0,0.04); 
    margin-bottom: 20px;
}
.app-card-title {
    margin-top: 0;
    margin-bottom: 20px; 
    color: var(--dark); 
    border-bottom: 2px solid #cbd5e1; 
    padding-bottom: 12px;
    font-size: 1.15rem;
}
.info-row {
    display: flex; 
    justify-content: space-between; 
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px solid #cbd5e1;
}
.info-row:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}
.info-label {
    color: #64748b; 
    font-weight: 600;
    font-size: 0.9rem;
}
.info-value {
    font-weight: 600; 
    color: var(--dark);
    font-size: 0.95rem;
    text-align: right;
}
.app-btn {
    flex: 1; 
    text-align: center; 
    padding: 12px 15px; 
    border-radius: 8px; 
    text-decoration: none; 
    font-weight: 600; 
    font-size: 0.95rem;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: none;
    cursor: pointer;
    box-sizing: border-box;
    gap: 6px;
}
.app-btn-dark {
    background: var(--dark); 
    color: #fff;
}
.app-btn-whatsapp {
    background: #25D366; 
    color: #fff;
}
.app-btn-success {
    background: #10b981;
    color: #fff;
}
.app-btn-light {
    background: #f1f5f9;
    color: #475569;
}
.timeline-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
}
.timeline-card {
    margin-bottom: 0;
    border-left: 4px solid var(--primary);
}
.timeline-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    flex-wrap: wrap;
    gap: 10px;
}

@media (max-width: 992px) {
    .app-layout-grid {
        grid-template-columns: 1fr;
        gap: 20px;
    }
}
@media (max-width: 768px) {
    .lead-title {
        font-size: 1.5rem;
    }
    .lead-header-container {
        flex-direction: column;
        align-items: stretch;
    }
    .lead-header-actions {
        width: 100%;
        display: grid !important;
        grid-template-columns: 1fr 1fr;
        gap: 8px;
    }
    /* Back and Edit take full row each */
    .lead-header-actions .btn-back,
    .lead-header-actions .btn-edit {
        grid-column: 1 / -1;
        justify-content: center;
        text-align: center;
    }
    .app-card {
        padding: 15px;
    }
    .timeline-header {
        flex-direction: column;
    }
    .timeline-badge-wrapper {
        margin-top: 5px;
    }
}
/* Dark borders for all form fields on this page */
.dashboard-content input[type="text"],
.dashboard-content input[type="email"],
.dashboard-content input[type="date"],
.dashboard-content input[type="time"],
.dashboard-content input[type="url"],
.dashboard-content select,
.dashboard-content textarea,
#meetingModal input,
#meetingModal select,
#meetingModal textarea,
#convertModal input,
#convertModal select,
#convertModal textarea {
    border: 2px solid #94a3b8 !important;
    border-radius: 8px !important;
}
#meetingModal input:focus,
#meetingModal select:focus,
#meetingModal textarea:focus,
#convertModal input:focus,
#convertModal select:focus,
#convertModal textarea:focus,
.dashboard-content input:focus,
.dashboard-content select:focus,
.dashboard-content textarea:focus {
    border-color: var(--primary) !important;
    outline: none;
}
</style>

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

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

