<?php
// =============================================
// SHARK CRM - Single Lead View Page
// =============================================

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

// Fetch lead data
$lead_query = $conn->query("
    SELECT l.*, c.customer_name, c.business_name,
           i.name as item_name, i.price as item_price, i.currency as item_currency, i.image as item_image,
           s.name as stage_name, s.color as stage_color,
           u.name as assigned_name, au.name as added_by_name
    FROM leads l
    LEFT JOIN customers c ON l.customer_id = c.id
    LEFT JOIN items i ON l.item_id = i.id
    LEFT JOIN stage s ON l.stage_id = s.id
    LEFT JOIN users u ON l.assigned_user_id = u.id
    LEFT JOIN users au ON l.created_by_user_id = au.id
    WHERE l.id = $lead_id AND l.account_id = $account_id AND l.datetime_deleted IS NULL
");

if ($lead_query->num_rows === 0) {
    header('Location: index.php?page=leads');
    exit;
}

$lead = $lead_query->fetch_assoc();

// Fetch customer contacts
$customer_contacts = $conn->query("
    SELECT id, name, job_title, phone, email, datetime_created 
    FROM customer_contacts 
    WHERE customer_id = " . (int)$lead['customer_id'] . "
    ORDER BY name
");

// Fetch followups
$followups = $conn->query("
    SELECT f.*, u.name as user_name 
    FROM lead_followup f 
    LEFT JOIN users u ON f.user_id = u.id 
    WHERE f.lead_id = $lead_id 
    ORDER BY f.datetime DESC
");

// Fetch activities
$activities = $conn->query("
    SELECT a.*, u.name as user_name, at.name as type_name 
    FROM lead_activities a 
    LEFT JOIN users u ON a.user_id = u.id 
    LEFT JOIN activity_type at ON a.activity_type_id = at.id 
    WHERE a.lead_id = $lead_id 
    ORDER BY a.datetime DESC
");

// For forms
$activity_types = $conn->query("SELECT id, name FROM activity_type ORDER BY name");
$stages_list = $conn->query("SELECT id, name, color FROM stage WHERE account_id = $account_id ORDER BY position");
$users_list = $conn->query("SELECT id, name FROM users WHERE account_id = $account_id ORDER BY name");


$reminders = $conn->query("
    SELECT r.*, u.name as user_name, at.name as type_name
    FROM reminder r
    LEFT JOIN users u ON r.user_id = u.id
    LEFT JOIN activity_type at ON r.activity_type_id = at.id
    WHERE r.lead_id = $lead_id AND r.account_id = $account_id
    ORDER BY r.date DESC, r.time DESC
");


?>

<div class="fade-in">
    <!-- Header with actions -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px;">
        <div>
            <a href="?page=leads" style="display: inline-flex; align-items: center; gap: 8px; margin-bottom: 12px; color: var(--text); text-decoration: none;">
                ← Back to Leads
            </a>
            <h1 style="margin: 0; font-size: 28px;"><?= htmlspecialchars($lead['title'] ?? 'Lead #' . $lead_id) ?></h1>
            <p style="color: var(--text-muted); margin-top: 8px;">Lead ID: #<?= $lead_id ?></p>
        </div>
        <div style="display: flex; gap: 12px;">
            
            <button class="btn btn-danger" data-page="leads" data-permission="delete" onclick="deleteLead(<?= $lead_id ?>)">🗑️ Delete</button>
        </div>
    </div>

    <!-- Main Content Grid -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
        <!-- Left Column - Lead Info -->
        <div class="card" style="padding: 20px;">
            <h3 style="margin-top: 0; margin-bottom: 20px;">Lead Information</h3>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                <div>
                    <label class="form-label">Customer</label>
                    <p><strong><?= htmlspecialchars($lead['customer_name'] ?? 'N/A') ?></strong></p>
                    <?php if ($lead['business_name']): ?>
                        <p class="text-xs text-muted"><?= htmlspecialchars($lead['business_name']) ?></p>
                    <?php endif; ?>
                </div>
                
                <div>
                    <label class="form-label">Item / Product</label>
                    <p><?= htmlspecialchars($lead['item_name'] ?? '—') ?></p>
                    <?php if ($lead['item_price']): ?>
                        <p class="text-xs text-muted"><?= crmMoney($lead['item_price'], $lead['item_currency'] ?: 'USD') ?></p>
                    <?php endif; ?>
                </div>
                
                <div>
                    <label class="form-label">Stage</label>
                    <div style="display: flex; gap: 8px; align-items: center;">
                        <span class="stage-pill" id="currentStage" style="background: <?= $lead['stage_color'] ?>22; color: <?= $lead['stage_color'] ?>; padding: 4px 12px; border-radius: 20px; font-size: 13px;">
                            <?= htmlspecialchars($lead['stage_name'] ?? 'N/A') ?>
                        </span>
                        
                    </div>
                </div>
                
                <div>
                    <label class="form-label">Estimated Price</label>
                    <p class="text-accent" style="font-weight: bold; color: var(--accent);"><?= crmMoney($lead['estimated_price'], $lead['item_currency'] ?: 'USD') ?></p>
                </div>
                
                <div>
                    <label class="form-label">Opportunity</label>
                    <div class="progress-wrap" style="background: var(--border); border-radius: 10px; overflow: hidden;">
                        <div class="progress-bar" style="width: <?= $lead['opportunity'] ?>%; height: 8px; background: var(--accent);"></div>
                    </div>
                    <div class="text-xs text-muted"><?= $lead['opportunity'] ?>%</div>
                </div>
                
                <div>
                    <label class="form-label">Priority</label>
                    <div><?= renderStars($lead['priority']) ?></div>
                </div>
                
                <div>
                    <label class="form-label">Added By</label>
                    <p><?= htmlspecialchars($lead['added_by_name'] ?? $lead['assigned_name'] ?? 'Unassigned') ?></p>
                </div>
                
                <div>
                    <label class="form-label">Created Date</label>
                    <p class="text-muted text-sm"><?= formatDate($lead['datetime_created']) ?></p>
                </div>
                
                <div>
                    <label class="form-label">Last Modified</label>
                    <p class="text-muted text-sm"><?= formatDate($lead['datetime_modified']) ?></p>
                </div>
            </div>

            <!-- Customer Contacts Section -->
            <?php if ($customer_contacts && $customer_contacts->num_rows > 0): ?>
            <div style="margin-top: 24px;">
                <div class="hr"></div>
                <h4 style="margin: 16px 0 12px 0;">📞 Customer Contacts</h4>
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <?php while ($contact = $customer_contacts->fetch_assoc()): ?>
                    <div style="padding: 12px; background: var(--bg-secondary); border-radius: 8px;">
                        <strong><?= htmlspecialchars($contact['name']) ?></strong>
                        <?php if ($contact['job_title']): ?> - <?= htmlspecialchars($contact['job_title']) ?><?php endif; ?>
                        <?php if ($contact['phone']): ?>
                        <div>📞 <?= htmlspecialchars($contact['phone']) ?></div>
                        <?php endif; ?>
                        <?php if ($contact['email']): ?>
                        <div>✉️ <?= htmlspecialchars($contact['email']) ?></div>
                        <?php endif; ?>
                    </div>
                    <?php endwhile; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Note Section -->
            <div style="margin-top: 24px;">
                <div class="hr"></div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin: 16px 0 12px 0;">
                    <h4 style="margin: 0;">📝 Note</h4>
                </div>
                <div style="background: var(--bg-secondary, #f9f9f9); border-radius: 8px; padding: 16px; min-height: 100px;">
                    <?php if ($lead['note']): ?>
                        <?= nl2br(htmlspecialchars($lead['note'])) ?>
                    <?php else: ?>
                        <p class="text-muted text-sm">No note added yet.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Right Column - Timeline & Activities -->
        <div class="card" style="padding: 20px;">
            <h3 style="margin-top: 0; margin-bottom: 20px;">Timeline & Comments</h3>
            
            <div class="tabs" style="display: flex; gap: 8px; border-bottom: 1px solid var(--border); margin-bottom: 16px;">
                <button class="tab-btn active" data-tab="tab-followups" style="padding: 8px 16px; background: none; border: none; cursor: pointer; border-bottom: 2px solid var(--accent); color: var(--accent);">💬 Comments (<?= $followups->num_rows ?>)</button>
                <button class="tab-btn" data-tab="tab-activities" style="padding: 8px 16px; background: none; border: none; cursor: pointer;">✅ Take Action (<?= $activities->num_rows ?>)</button>
                
                <button class="tab-btn" data-tab="tab-reminders" style="padding: 8px 16px; background: none; border: none; cursor: pointer;">
    ⏰ Reminders (<?= $reminders->num_rows ?>)
</button>
                <button class="tab-btn" data-tab="tab-contact" style="padding: 8px 16px; background: none; border: none; cursor: pointer;">📨 Contact</button>

            </div>

            <!-- Comments Tab -->
            <div class="tab-pane active" id="tab-followups">
                <div id="followupsTimeline" style="max-height: 400px; overflow-y: auto;">
                    <?php if ($followups->num_rows === 0): ?>
                        <p class="text-muted text-sm" style="padding: 20px; text-align: center;">No comments yet</p>
                    <?php else: ?>
                        <?php while ($f = $followups->fetch_assoc()): ?>
                        <div class="timeline-item" style="display: flex; gap: 12px; margin-bottom: 16px;">
                            <div class="timeline-dot" style="flex-shrink: 0; width: 32px; height: 32px; background: var(--bg-secondary); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
                                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                                </svg>
                            </div>
                            <div class="timeline-content" style="flex: 1; background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px;">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                    <span style="font-weight: 600; font-size: 13px;"><?= htmlspecialchars($f['user_name'] ?? 'User') ?></span>
                                    <span style="font-size: 11px; color: var(--text-muted);"><?= formatDate($f['datetime']) ?></span>
                                </div>
                                <div style="font-size: 14px; line-height: 1.5;"><?= nl2br(htmlspecialchars($f['comment'])) ?></div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </div>
                <div class="hr" style="height: 1px; background: var(--border); margin: 16px 0;"></div>
                <div class="form-group mb-0">
                    <textarea id="newComment" class="form-control" placeholder="Add a comment..." rows="3" style="width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 6px;"></textarea>
                </div>
                <button class="btn btn-primary btn-sm" data-page="leads" data-permission="take_action" style="margin-top: 8px; padding: 6px 12px;" onclick="addFollowup(<?= $lead_id ?>)">Post Comment</button>
            </div>

            <!-- Activities Tab -->
            <div class="tab-pane" id="tab-activities" style="display: none;">
                <div id="activitiesTimeline" style="max-height: 400px; overflow-y: auto;">
                    <?php if ($activities->num_rows === 0): ?>
                        <p class="text-muted text-sm" style="padding: 20px; text-align: center;">No activities yet</p>
                    <?php else: ?>
                        <?php while ($a = $activities->fetch_assoc()): ?>
                        <div class="timeline-item" style="display: flex; gap: 12px; margin-bottom: 16px;">
                            <div class="timeline-dot" style="flex-shrink: 0; width: 32px; height: 32px; background: var(--bg-secondary); border-radius: 50%; display: flex; align-items: center; justify-content: center;">📌</div>
                            <div class="timeline-content" style="flex: 1; background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px;">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                    <span style="font-weight: 600; font-size: 13px;"><?= htmlspecialchars($a['type_name'] ?? 'Activity') ?></span>
                                    <span style="font-size: 11px; color: var(--text-muted);"><?= formatDate($a['datetime']) ?></span>
                                </div>
                                <div style="font-size: 14px; line-height: 1.5;"><?= nl2br(htmlspecialchars($a['text'] ?? '')) ?></div>
                                <?php if ($a['date_activitie']): ?>
                                <div style="font-size: 12px; color: var(--text-muted); margin-top: 8px;">Due: <?= formatDate($a['date_activitie']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </div>
                <div class="hr" style="height: 1px; background: var(--border); margin: 16px 0;"></div>
                <label class="form-label">Take Action</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
                    <select id="actType" class="form-control" style="padding: 8px;">
                        <?php $activity_types->data_seek(0); while ($at = $activity_types->fetch_assoc()): ?>
                        <option value="<?= $at['id'] ?>"><?= htmlspecialchars($at['name']) ?></option>
                        <?php endwhile; ?>
                    </select>
                    <input type="date" id="actdate" class="form-control" style="padding: 8px;">
                </div>
                <textarea id="actText" class="form-control" placeholder="Comment: shu sar ma3 el customer / lead..." rows="2" style="width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 6px;"></textarea>
                <button class="btn btn-secondary btn-sm" data-page="leads" data-permission="take_action" style="margin-top: 8px; padding: 6px 12px;" onclick="logActivity(<?= $lead_id ?>)">Save Action</button>
            </div>
            
            <div class="tab-pane" id="tab-reminders" style="display: none;">
    <div style="max-height: 400px; overflow-y: auto;">
        <?php if ($reminders->num_rows === 0): ?>
            <p class="text-muted text-sm" style="padding: 20px; text-align: center;">No reminders yet</p>
        <?php else: ?>
            <?php while ($r = $reminders->fetch_assoc()): ?>
                <div class="timeline-item" style="display:flex; gap:12px; margin-bottom:16px;">
                    <div class="timeline-dot" style="width:32px;height:32px;background:var(--bg-secondary);border-radius:50%;display:flex;align-items:center;justify-content:center;">⏰</div>
                    <div style="flex:1;background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px 14px;">
                        <div style="display:flex;justify-content:space-between;margin-bottom:8px;">
                            <strong><?= htmlspecialchars($r['type_name'] ?? 'Reminder') ?></strong>
                            <span class="text-muted text-xs">
                                <?= htmlspecialchars($r['date']) ?>
                                <?= $r['time'] ? htmlspecialchars(substr($r['time'], 0, 5)) : '' ?>
                            </span>
                        </div>
                        <div><?= nl2br(htmlspecialchars($r['comment'] ?? '')) ?></div>
                        <div class="text-xs text-muted" style="margin-top:8px;">
                            Status: <?= htmlspecialchars($r['status']) ?>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php endif; ?>
    </div>

    <div class="hr"></div>

    <label class="form-label">Add Reminder</label>

    <div style="display:grid; grid-template-columns: 1fr 1fr; gap:12px; margin-bottom:12px;">
        <input type="date" id="reminderDate" class="form-control" style="padding:8px;">
        <input type="time" id="reminderTime" class="form-control" style="padding:8px;">
    </div>

    <select id="reminderType" class="form-control" style="padding:8px; margin-bottom:12px;">
        <?php $activity_types->data_seek(0); while ($at = $activity_types->fetch_assoc()): ?>
            <option value="<?= $at['id'] ?>"><?= htmlspecialchars($at['name']) ?></option>
        <?php endwhile; ?>
    </select>

    <textarea id="reminderComment" class="form-control" placeholder="Reminder note..." rows="2" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;"></textarea>

    <button class="btn btn-primary btn-sm" data-page="reminders" data-permission="add" style="margin-top:8px;" onclick="addReminder(<?= $lead_id ?>)">
        Add Reminder
    </button>


            <div class="tab-pane" id="tab-contact" style="display:none;">
                <div class="lead-contact-tabs">
                    <button type="button" class="lead-contact-tab active" data-contact-type="whatsapp" onclick="selectLeadContactType('whatsapp')">WhatsApp</button>
                    <button type="button" class="lead-contact-tab" data-contact-type="email" onclick="selectLeadContactType('email')">Email</button>
                </div>
                <input type="hidden" id="leadContactType" value="whatsapp">
                <input type="hidden" id="leadContactLeadId" value="<?= $lead_id ?>">
                <input type="hidden" id="leadContactCustomerId" value="<?= (int)$lead['customer_id'] ?>">
                <div id="leadEmailSubjectWrap" class="form-group" style="display:none;margin-top:12px;">
                    <label class="form-label">Email Subject</label>
                    <input id="leadContactSubject" class="form-control" value="About <?= htmlspecialchars($lead['item_name'] ?: 'your requested item') ?>" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;">
                </div>
                <div class="form-group" style="margin-top:12px;">
                    <label class="form-label">Prepared message</label>
                    <textarea id="leadContactMsg" class="form-control" rows="6" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;">Hello <?= htmlspecialchars($lead['customer_name'] ?: 'dear') ?>,

Regarding your interest in <?= htmlspecialchars($lead['item_name'] ?: 'our item') ?>, the price is <?= htmlspecialchars(crmMoney($lead['estimated_price'], $lead['item_currency'] ?: 'USD')) ?>.

Would you like more details?</textarea>
                </div>
                <label class="lead-check"><input type="checkbox" id="leadIncludeItemImage" checked> Include item image if available</label>
                <div class="form-group" style="margin-top:10px;">
                    <label class="form-label">Or upload new image</label>
                    <input type="file" id="leadContactMedia" accept="image/*" class="form-control" onchange="previewLeadContactImage(this)" style="width:100%;padding:8px;border:1px solid var(--border);border-radius:6px;">
                </div>
                <div id="leadContactPreview" class="lead-whatsapp-preview">
                    <div class="wa-head">WhatsApp Preview</div>
                    <img id="leadContactPreviewImg" style="display:none" alt="Preview">
                    <div id="leadContactPreviewText" class="wa-bubble"></div>
                </div>
                <button class="btn btn-primary" style="margin-top:12px;" onclick="sendLeadContactFromView()">📨 Send</button>
            </div>
        </div>
    </div>
</div>

<!-- Stage Change Modal -->
<div class="modal-overlay" id="stageModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); align-items: center; justify-content: center; z-index: 1000;">
    <div class="modal" style="max-width: 450px; width: 100%; background: var(--bg-card); border-radius: 12px; padding: 0; margin: 20px;">
        <div class="modal-header" style="display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid var(--border);">
            <span class="modal-title" style="font-size: 18px; font-weight: 600;">🔄 Change Stage</span>
            <button class="modal-close" onclick="closeModal('stageModal')" style="background: none; border: none; font-size: 24px; cursor: pointer;">✕</button>
        </div>
        <div class="modal-body" style="padding: 20px;">
            <input type="hidden" id="stageLeadId" value="">
            <div class="form-group mb-0">
                <label class="form-label">Select Stage</label>
                <select id="stageSelectModal" class="form-control" style="width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 6px;">
                    <?php $stages_list->data_seek(0); while ($stage = $stages_list->fetch_assoc()): ?>
                    <option value="<?= $stage['id'] ?>" data-color="<?= $stage['color'] ?>">
                        <?= htmlspecialchars($stage['name']) ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
        </div>
        <div class="modal-footer" style="display: flex; justify-content: flex-end; gap: 12px; padding: 16px 20px; border-top: 1px solid var(--border);">
            <button class="btn btn-secondary" onclick="closeModal('stageModal')">Cancel</button>
            <button class="btn btn-primary" data-page="leads" data-permission="move_stage" onclick="updateStage()">Update Stage</button>
        </div>
    </div>
</div>

<!-- Edit Note Modal -->
<div class="modal-overlay" id="noteModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); align-items: center; justify-content: center; z-index: 1000;">
    <div class="modal" style="max-width: 600px; width: 100%; background: var(--bg-card); border-radius: 12px; padding: 0; margin: 20px;">
        <div class="modal-header" style="display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid var(--border);">
            <span class="modal-title" style="font-size: 18px; font-weight: 600;">📝 Edit Note</span>
            <button class="modal-close" onclick="closeModal('noteModal')" style="background: none; border: none; font-size: 24px; cursor: pointer;">✕</button>
        </div>
        <div class="modal-body" style="padding: 20px;">
            <input type="hidden" id="noteLeadId" value="<?= $lead_id ?>">
            <div class="form-group mb-0">
                <label class="form-label">Note</label>
                <textarea id="noteTextarea" class="form-control" rows="8" placeholder="Write your note here..." style="width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 6px;"></textarea>
            </div>
        </div>
        <div class="modal-footer" style="display: flex; justify-content: flex-end; gap: 12px; padding: 16px 20px; border-top: 1px solid var(--border);">
            <button class="btn btn-secondary" onclick="closeModal('noteModal')">Cancel</button>
            <button class="btn btn-primary" data-page="leads" data-permission="edit" onclick="saveNote()">💾 Save Note</button>
        </div>
    </div>
</div>

<script>
// Edit Lead - redirect to leads page with edit mode
function editLead(id) {
    window.location.href = '?page=leads&edit_id=' + id;
}

// Delete Lead
async function deleteLead(id) {
    if (!confirm('Delete this lead? This cannot be undone.')) return;
    const res = await apiCall('handlers/leads.php', { action: 'delete', id });
    if (res.success) {
        showToast('Lead deleted', 'success');
        setTimeout(() => window.location.href = '?page=leads', 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// Open Stage Modal
function openStageModal(leadId, currentStageId) {
    document.getElementById('stageLeadId').value = leadId;
    const select = document.getElementById('stageSelectModal');
    select.value = currentStageId;
    openModal('stageModal');
}

// Update Stage
async function updateStage() {
    const leadId = document.getElementById('stageLeadId').value;
    const stageId = document.getElementById('stageSelectModal').value;
    const stageName = document.getElementById('stageSelectModal').options[document.getElementById('stageSelectModal').selectedIndex].text;
    const stageColor = document.getElementById('stageSelectModal').options[document.getElementById('stageSelectModal').selectedIndex].dataset.color;
    
    const res = await apiCall('handlers/leads.php', { action: 'move_stage', lead_id: leadId, stage_id: stageId });
    if (res.success) {
        showToast(`Stage updated to ${stageName}`, 'success');
        // Update the stage pill without reloading
        const stagePill = document.getElementById('currentStage');
        stagePill.textContent = stageName;
        stagePill.style.background = `${stageColor}22`;
        stagePill.style.color = stageColor;
        closeModal('stageModal');
        // Optional: reload to refresh activities
        setTimeout(() => location.reload(), 800);
    } else {
        showToast(res.message || 'Error updating stage', 'error');
    }
}

// Edit Note Modal
function editNote(leadId, currentNote) {
    document.getElementById('noteLeadId').value = leadId;
    document.getElementById('noteTextarea').value = currentNote || '';
    openModal('noteModal');
}

async function saveNote() {
    const leadId = document.getElementById('noteLeadId').value;
    const note = document.getElementById('noteTextarea').value;
    const res = await apiCall('handlers/leads.php', { action: 'save_note', id: leadId, note: note });
    if (res.success) {
        showToast('Note saved!', 'success');
        closeModal('noteModal');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error saving note', 'error');
    }
}

// Add Followup
async function addFollowup(leadId) {
    const comment = document.getElementById('newComment').value.trim();
    if (!comment) { showToast('Please enter a comment', 'warning'); return; }
    const res = await apiCall('handlers/leads.php', { action: 'add_followup', lead_id: leadId, comment: comment });
    if (res.success) {
        showToast('Comment added', 'success');
        document.getElementById('newComment').value = '';
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// Log Activity
async function logActivity(leadId) {
    const typeId = document.getElementById('actType').value;
    const text = document.getElementById('actText').value.trim();
    const comment = text;
    const actdate = document.getElementById('actdate').value;
    
    if (!text) { showToast('Please enter activity notes', 'warning'); return; }
    if (!actdate) { showToast('Please select activity date', 'warning'); return; }
    
    const res = await apiCall('handlers/leads.php', { 
        action: 'add_activity', 
        lead_id: leadId, 
        activity_type_id: typeId, 
        text: text,
        comment: comment,
        actdate: actdate 
    });
    
    if (res.success) {
        showToast('Activity logged', 'success');
        document.getElementById('actText').value = '';
        document.getElementById('actdate').value = '';
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// Helper Functions
function openModal(modalId) {
    document.getElementById(modalId).style.display = 'flex';
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

function showToast(message, type) {
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 8px;
        background: ${type === 'error' ? '#ef4444' : (type === 'success' ? '#10b981' : '#f59e0b')};
        color: white;
        z-index: 9999;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        animation: slideIn 0.3s ease;
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

async function apiCall(url, data) {
    const formData = new FormData();
    for (let key in data) {
        formData.append(key, data[key]);
    }
    const response = await fetch(url, { method: 'POST', body: formData });
    return await response.json();
}

// Initialize Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        const tabId = btn.dataset.tab;
        document.querySelectorAll('.tab-btn').forEach(b => {
            b.style.borderBottom = 'none';
            b.style.color = 'var(--text)';
        });
        document.querySelectorAll('.tab-pane').forEach(p => p.style.display = 'none');
        btn.style.borderBottom = '2px solid var(--accent)';
        btn.style.color = 'var(--accent)';
        document.getElementById(tabId).style.display = 'block';
    });
});


async function addReminder(leadId) {
    const date = document.getElementById('reminderDate').value;
    const time = document.getElementById('reminderTime').value;
    const comment = document.getElementById('reminderComment').value.trim();
    const typeId = document.getElementById('reminderType').value;

    if (!date) { showToast('Please select reminder date', 'warning'); return; }
    if (!comment) { showToast('Please enter reminder note', 'warning'); return; }

    const res = await apiCall('handlers/leads.php', {
        action: 'add_reminder',
        lead_id: leadId,
        date: date,
        time: time,
        comment: comment,
        activity_type_id: typeId
    });

    if (res.success) {
        showToast('Reminder added', 'success');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}


function selectLeadContactType(type){
    document.getElementById('leadContactType').value = type;
    document.querySelectorAll('.lead-contact-tab').forEach(b=>b.classList.toggle('active', b.dataset.contactType===type));
    document.getElementById('leadEmailSubjectWrap').style.display = type === 'email' ? 'block' : 'none';
    document.querySelector('.wa-head').textContent = type === 'email' ? 'Email Preview' : 'WhatsApp Preview';
    updateLeadContactPreview();
}
function previewLeadContactImage(input){
    const img = document.getElementById('leadContactPreviewImg');
    const f = input.files && input.files[0];
    if(!f){ img.style.display='none'; img.src=''; return; }
    img.src = URL.createObjectURL(f); img.style.display='block';
}
function updateLeadContactPreview(){
    const msg = document.getElementById('leadContactMsg');
    const box = document.getElementById('leadContactPreviewText');
    if(box && msg) box.textContent = msg.value;
}
document.getElementById('leadContactMsg')?.addEventListener('input', updateLeadContactPreview);
updateLeadContactPreview();
async function sendLeadContactFromView(){
    const fd = new FormData();
    fd.append('action','send');
    fd.append('target_type','lead');
    fd.append('lead_id',document.getElementById('leadContactLeadId').value);
    fd.append('customer_id',document.getElementById('leadContactCustomerId').value);
    fd.append('type',document.getElementById('leadContactType').value);
    fd.append('subject',document.getElementById('leadContactSubject')?.value || 'About your requested item');
    fd.append('message',document.getElementById('leadContactMsg').value);
    fd.append('include_item_image',document.getElementById('leadIncludeItemImage').checked?'1':'0');
    const media = document.getElementById('leadContactMedia').files[0]; if(media) fd.append('media',media);
    const res = await fetch('handlers/communications.php',{method:'POST',body:fd}).then(r=>r.json()).catch(()=>({success:false,message:'Server error'}));
    if(res.success){ showToast('Message sent','success'); } else { showToast(res.message || 'Send failed', 'error'); }
}

</script>

<style>
.card {
    background: var(--bg-card);
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.form-label {
    display: block;
    margin-bottom: 4px;
    font-size: 12px;
    font-weight: 500;
    color: var(--text-muted);
}

.text-xs { font-size: 12px; }
.text-sm { font-size: 13px; }
.text-muted { color: var(--text-muted); }
.text-accent { color: var(--accent); }

.btn {
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    border: none;
}

.btn-primary {
    background: var(--accent);
    color: white;
}

.btn-secondary {
    background: var(--bg-secondary);
    border: 1px solid var(--border);
}

.btn-danger {
    background: #ef4444;
    color: white;
}

.btn-sm {
    padding: 4px 12px;
    font-size: 12px;
}

.hr {
    height: 1px;
    background: var(--border);
    margin: 16px 0;
}

.lead-contact-tabs{display:flex;gap:8px;background:var(--bg-secondary);padding:6px;border-radius:12px;margin-bottom:12px}.lead-contact-tab{border:0;background:transparent;padding:10px 14px;border-radius:10px;cursor:pointer;font-weight:700;color:var(--text)}.lead-contact-tab.active{background:var(--accent);color:white}.lead-check{display:flex;align-items:center;gap:8px;margin-top:8px;font-size:13px;color:var(--text)}.lead-whatsapp-preview{margin-top:12px;border:1px solid var(--border);border-radius:14px;background:#f0f7f2;padding:12px}.lead-whatsapp-preview .wa-head{font-size:12px;font-weight:800;color:#28624a;margin-bottom:8px}.lead-whatsapp-preview img{max-width:220px;max-height:160px;object-fit:cover;border-radius:10px;margin-bottom:8px}.lead-whatsapp-preview .wa-bubble{display:inline-block;max-width:100%;white-space:pre-wrap;background:#dcf8c6;border-radius:14px 14px 2px 14px;padding:10px 12px;color:#111;line-height:1.45}.form-control{box-sizing:border-box}

</style>