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

// Actions BEFORE any output to avoid headers-already-sent
if (isset($_GET['action']) && isset($_GET['id'])) {
    $f_id   = (int)$_GET['id'];
    $action = $_GET['action'];
    if (in_array($action, ['completed', 'cancelled'])) {
        $pdo->prepare("UPDATE lead_followups SET status = ? WHERE id = ?")->execute([$action, $f_id]);
        $qs = array_diff_key($_GET, ['action'=>'','id'=>'']);
        header("Location: lead_followups.php?" . http_build_query($qs) . "&msg=updated");
        exit;
    }
}

// Complete Follow-up with outcome + optional next step (POST)
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'] ?? '');
    
    // Find lead_id for this follow-up
    $fup_data = $pdo->prepare("SELECT lead_id FROM lead_followups WHERE id = ?");
    $fup_data->execute([$f_id]);
    $f_lead = $fup_data->fetch();
    
    if ($f_lead) {
        $lead_id = $f_lead['lead_id'];
        try {
            $pdo->beginTransaction();
            $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]);
            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, status) VALUES (?,?,?, 'pending')")
                    ->execute([$lead_id, $next_date.' '.$next_time.':00', $next_notes]);
            }
            $pdo->commit();
            header("Location: lead_followups.php?msg=updated");
            exit;
        } catch (PDOException $e) { $pdo->rollBack(); $error = "Error: " . $e->getMessage(); }
    }
}

require_once 'includes/header.php';

if (isset($_GET['msg']) && $_GET['msg'] === 'updated') $success = "Follow-up status updated.";

// ---- Filters ----
$today    = date('Y-m-d');
$now      = date('Y-m-d H:i:s');
$f_type   = $_GET['type']      ?? 'upcoming';
$f_period = $_GET['period']    ?? '';
$f_from   = $_GET['date_from'] ?? '';
$f_to     = $_GET['date_to']   ?? '';

$where  = "l.is_junk = 0";
$params = [];

if ($f_type === 'upcoming')     { $where .= " AND f.status='pending' AND f.followup_date >= ?";  $params[] = $now; }
elseif ($f_type === 'missed')   { $where .= " AND f.status='pending' AND f.followup_date < ?";   $params[] = $now; }
elseif ($f_type === 'done')     { $where .= " AND f.status='completed'"; }
elseif ($f_type === 'cancelled'){ $where .= " AND f.status='cancelled'"; }

if      ($f_period === 'today')      { $where .= " AND DATE(f.followup_date)=?"; $params[] = $today; }
elseif  ($f_period === 'tomorrow')   { $where .= " AND DATE(f.followup_date)=DATE_ADD(?,INTERVAL 1 DAY)"; $params[] = $today; }
elseif  ($f_period === 'this_week')  { $where .= " AND YEARWEEK(f.followup_date,1)=YEARWEEK(?,1)"; $params[] = $today; }
elseif  ($f_period === 'this_month') { $where .= " AND MONTH(f.followup_date)=MONTH(?) AND YEAR(f.followup_date)=YEAR(?)"; $params[]=$today; $params[]=$today; }
elseif  ($f_period === 'custom' && $f_from && $f_to){ $where .= " AND DATE(f.followup_date) BETWEEN ? AND ?"; $params[]=$f_from; $params[]=$f_to; }

$order = ($f_type === 'done') ? "f.followup_date DESC" : "f.followup_date ASC";

$stmt = $pdo->prepare("SELECT f.*, l.name as lead_name, l.phone as lead_phone FROM lead_followups f JOIN leads l ON f.lead_id=l.id WHERE $where ORDER BY $order");
$stmt->execute($params);
$followups = $stmt->fetchAll();

$counts = $pdo->query("SELECT SUM(f.status='pending' AND f.followup_date>=NOW()) as upcoming, SUM(f.status='pending' AND f.followup_date<NOW()) as missed, SUM(f.status='completed') as done, SUM(f.status='cancelled') as cancelled FROM lead_followups f JOIN leads l ON f.lead_id=l.id WHERE l.is_junk=0")->fetch();

$all_statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY id ASC")->fetchAll();

function fUrl($type, $period='', $from='', $to='') {
    $q = ['type' => $type];
    if ($period) $q['period'] = $period;
    if ($from)   $q['date_from'] = $from;
    if ($to)     $q['date_to'] = $to;
    return 'lead_followups.php?' . http_build_query($q);
}
?>

<style>
/* ---- Same style as leads.php ---- */
.btn-3d {
    display: inline-flex; align-items: center; justify-content: center;
    width: 36px; height: 36px; border-radius: 8px; text-decoration: none;
    transition: all 0.1s ease; position: relative; top: 0;
    border: none; cursor: pointer; margin-left: 6px;
}
.btn-3d-view   { background:#3b82f6; color:#fff; box-shadow:0 4px 0 #2563eb, 0 5px 8px rgba(0,0,0,0.15); }
.btn-3d-done   { background:#22c55e; color:#fff; box-shadow:0 4px 0 #16a34a, 0 5px 8px rgba(0,0,0,0.15); }
.btn-3d-cancel { background:#ef4444; color:#fff; box-shadow:0 4px 0 #dc2626, 0 5px 8px rgba(0,0,0,0.15); }
.btn-3d:active { top: 4px; box-shadow: none !important; }

@media (max-width: 768px) {
    /* Force compact ROW view — override the global card transform */
    .admin-table, .admin-table thead, .admin-table tbody,
    .admin-table th, .admin-table td, .admin-table tr {
        display: revert !important;
    }
    .admin-table { width:100%; border-collapse:collapse; }
    .admin-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
    .admin-table th, .admin-table td {
        padding: 10px 5px !important;
        font-size: 0.78rem !important;
        vertical-align: middle !important;
        min-height: auto !important;
        padding-left: 5px !important;
        border-bottom: 1px solid #f1f5f9 !important;
        border: none !important;
        border-bottom: 1px solid #f1f5f9 !important;
    }
    .admin-table tr {
        border: none !important;
        border-radius: 0 !important;
        margin-bottom: 0 !important;
        padding: 0 !important;
        box-shadow: none !important;
        display: table-row !important;
    }
    .admin-table td:before { display: none !important; content: none !important; }

    .mobile-actions-grid {
        display: flex !important;
        flex-direction: row !important;
        justify-content: flex-end !important;
        align-items: center !important;
        gap: 4px !important;
        padding-right: 8px !important;
        padding-left: 0 !important;
        width: auto !important;
    }
    .mobile-actions-grid .btn-3d { margin: 0 !important; width: 32px !important; height: 32px !important; font-size: 0.75rem !important; }
    .btn-3d { width: 32px !important; height: 32px !important; font-size: 0.75rem !important; margin-left: 3px !important; }
}

/* Tab chips */
.fup-type-bar { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:15px; }
.fup-type-chip {
    display:inline-flex; align-items:center; gap:6px; padding:8px 14px;
    border-radius:20px; font-weight:600; font-size:0.82rem;
    text-decoration:none; border:2px solid #e2e8f0;
    background:#f8fafc; color:#64748b; transition:all 0.18s; white-space:nowrap;
}
.fup-type-chip.active-upcoming { background:#3b82f6; color:#fff; border-color:#3b82f6; }
.fup-type-chip.active-missed   { background:#ef4444; color:#fff; border-color:#ef4444; }
.fup-type-chip.active-done     { background:#22c55e; color:#fff; border-color:#22c55e; }
.fup-type-chip.active-cancelled{ background:#94a3b8; color:#fff; border-color:#94a3b8; }
.fup-type-chip.active-all      { background:#8b5cf6; color:#fff; border-color:#8b5cf6; }
.fup-count { background:rgba(255,255,255,0.3); padding:1px 7px; border-radius:10px; font-size:0.75rem; font-weight:700; }
.fup-type-chip:not([class*="active"]) .fup-count { background:rgba(0,0,0,0.07); }

/* Date quick filters */
.date-pill-bar { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
.date-pill {
    padding:6px 14px; border-radius:20px; font-size:0.8rem; font-weight:600;
    text-decoration:none; background:#f1f5f9; color:#64748b;
    border:1px solid #e2e8f0; transition:all 0.15s;
}
.date-pill.active { background:var(--dark); color:#fff; border-color:var(--dark); }
</style>

<div class="dashboard-content">
    <!-- Header Banner -->
    <div class="welcome-banner" style="margin-bottom:20px; padding:20px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:15px;">
        <div>
            <h2><i class="fa-regular fa-calendar-check"></i> Follow-ups</h2>
            <p>Track upcoming, missed and completed follow-ups.</p>
        </div>
        <div style="background:rgba(255,255,255,0.15); padding:12px 20px; border-radius:10px; text-align:center;">
            <div style="font-size:1.6rem; font-weight:800;"><?= array_sum([$counts['upcoming']??0,$counts['missed']??0,$counts['done']??0]) ?></div>
            <div style="font-size:0.8rem; opacity:0.85;">Total Active</div>
        </div>
    </div>

    <?php if (!empty($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:12px 18px; margin-bottom:15px; font-size:0.95rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <!-- TYPE TABS -->
    <div class="fup-type-bar">
        <?php $tabs = [
            ['upcoming',  'Need to Follow Up', $counts['upcoming']  ?? 0, '#3b82f6', 'fa-clock'],
            ['missed',    'Missed',             $counts['missed']   ?? 0, '#ef4444', 'fa-triangle-exclamation'],
            ['done',      'Done',               $counts['done']     ?? 0, '#22c55e', 'fa-circle-check'],
            ['cancelled', 'Cancelled',          $counts['cancelled']?? 0, '#94a3b8', 'fa-circle-xmark'],
            ['all',       'All',                ($counts['upcoming']??0)+($counts['missed']??0)+($counts['done']??0)+($counts['cancelled']??0), '#8b5cf6', 'fa-list'],
        ];
        foreach ($tabs as [$type, $label, $count, $color, $icon]):
            $isActive = $f_type === $type;
        ?>
        <a href="<?= fUrl($type) ?>" class="fup-type-chip <?= $isActive ? 'active-'.$type : '' ?>">
            <i class="fa-solid <?= $icon ?>"></i> <?= $label ?>
            <span class="fup-count"><?= $count ?></span>
        </a>
        <?php endforeach; ?>
    </div>

    <!-- DATE QUICK FILTER -->
    <div class="date-pill-bar">
        <?php foreach(['today'=>'Today','tomorrow'=>'Tomorrow','this_week'=>'This Week','this_month'=>'This Month'] as $key=>$label): ?>
            <a href="<?= fUrl($f_type, $key) ?>" class="date-pill <?= $f_period===$key ? 'active' : '' ?>"><?= $label ?></a>
        <?php endforeach; ?>

        <!-- Custom date inline -->
        <form method="GET" style="display:inline-flex; gap:6px; align-items:center; flex-wrap:wrap;">
            <input type="hidden" name="type" value="<?= htmlspecialchars($f_type) ?>">
            <input type="hidden" name="period" value="custom">
            <input type="date" name="date_from" value="<?= htmlspecialchars($f_from) ?>" style="padding:6px 10px; border:1px solid var(--border); border-radius:20px; font-size:0.8rem; font-family:inherit;">
            <span style="color:#94a3b8; font-size:0.8rem;">—</span>
            <input type="date" name="date_to" value="<?= htmlspecialchars($f_to) ?>" style="padding:6px 10px; border:1px solid var(--border); border-radius:20px; font-size:0.8rem; font-family:inherit;">
            <button type="submit" class="date-pill" style="background:var(--primary); color:#fff; border:none; cursor:pointer;">Go</button>
            <?php if($f_period): ?>
                <a href="<?= fUrl($f_type) ?>" class="date-pill">Clear</a>
            <?php endif; ?>
        </form>
    </div>

    <!-- TABLE (same structure as leads.php) -->
    <div class="recent-activity" style="padding:0;">
        <div class="table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th style="padding-left:20px; width:60px;">S.No</th>
                        <th>Contact Number</th>
                        <th>Follow-up Date &amp; Time</th>
                        <th style="text-align:right; padding-right:20px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($followups) === 0): ?>
                        <tr>
                            <td colspan="4" style="text-align:center; padding:50px 20px; color:#94a3b8;">
                                <i class="fa-regular fa-calendar-check" style="font-size:2.5rem; color:#cbd5e1; display:block; margin-bottom:12px;"></i>
                                <?= $f_type==='upcoming' ? 'No upcoming follow-ups' : ($f_type==='missed' ? 'No missed follow-ups 🎉' : ($f_type==='done' ? 'No completed follow-ups yet' : 'No follow-ups found')) ?>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php $sno = 1; foreach ($followups as $f):
                            $fup_dt = strtotime($f['followup_date']);
                            $diff_s = $fup_dt - time();
                            $diff_d = (int)($diff_s / 86400);

                            if ($f['status'] === 'completed')      { $bc='#d1fae5'; $bcolor='#065f46'; $bt='Done'; }
                            elseif ($f['status'] === 'cancelled')  { $bc='#f1f5f9'; $bcolor='#64748b'; $bt='Cancelled'; }
                            elseif ($diff_s < 0)                   { $bc='#fee2e2'; $bcolor='#ef4444'; $bt=abs($diff_d).'d Overdue'; }
                            elseif ($diff_d === 0)                  { $bc='#fef3c7'; $bcolor='#d97706'; $bt='Today'; }
                            elseif ($diff_d === 1)                  { $bc='#fef3c7'; $bcolor='#d97706'; $bt='Tomorrow'; }
                            else                                   { $bc='#dbeafe'; $bcolor='#2563eb'; $bt='In '.$diff_d.'d'; }
                        ?>
                        <tr style="<?= ($f['status']==='pending' && $diff_s<0) ? 'background:#fff8f8;' : '' ?>">
                            <td style="padding-left:20px; color:#64748b; font-weight:500;">#<?= $sno++ ?></td>
                            <td>
                                <div style="font-weight:700; color:var(--dark); font-size:1.05rem;"><?= htmlspecialchars($f['lead_phone']) ?></div>
                                <span style="background:<?= $bc ?>; color:<?= $bcolor ?>; padding:2px 9px; border-radius:10px; font-size:0.75rem; font-weight:700;"><?= $bt ?></span>
                            </td>
                            <td style="color:#64748b;">
                                <div style="font-weight:600; color:var(--dark);"><?= date('d M Y', $fup_dt) ?></div>
                                <div style="font-size:0.82rem;"><?= date('h:i A', $fup_dt) ?></div>
                            </td>
                            <td style="text-align:right; padding-right:20px;" class="mobile-actions-grid">
                                <a href="lead_view.php?id=<?= $f['lead_id'] ?>" class="btn-3d btn-3d-view" title="View Lead"><i class="fa-solid fa-eye"></i></a>
                                <?php if ($f['status'] === 'pending'): ?>
                                    <button type="button" onclick="openFupModal(<?= $f['id'] ?>, '<?= htmlspecialchars($f['lead_phone']) ?>')" class="btn-3d btn-3d-done" title="Mark Done"><i class="fa-solid fa-check"></i></button>
                                    <a href="lead_followups.php?action=cancelled&id=<?= $f['id'] ?>&type=<?= $f_type ?>&period=<?= $f_period ?>" class="btn-3d btn-3d-cancel" title="Cancel" onclick="return confirm('Cancel this follow-up?')"><i class="fa-solid fa-xmark"></i></a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Complete Follow-up Modal -->
<div id="completeFupModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:9999; align-items:center; justify-content:center; padding:15px;">
    <div style="background:#fff; padding:30px; border-radius:16px; width:100%; max-width:520px; box-shadow:0 20px 60px rgba(0,0,0,0.3); max-height:95vh; overflow-y:auto;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; border-bottom:1px solid #f1f5f9; padding-bottom:12px;">
            <h3 style="margin:0; color:var(--dark); font-weight:800; font-size:1.2rem;"><i class="fa-solid fa-circle-check" style="color:#10b981; margin-right:10px;"></i>Complete Follow-up (<span id="modal_phone_display" style="color:var(--primary);"></span>)</h3>
            <button onclick="closeFupModal()" style="background:none; border:none; font-size:1.6rem; cursor:pointer; color:#94a3b8; line-height:1;">&times;</button>
        </div>
        
        <form action="lead_followups.php" method="POST">
            <input type="hidden" name="complete_followup_id" id="modal_fup_id" value="">
            
            <div style="margin-bottom: 15px;">
                <label style="display:block; margin-bottom:6px; font-weight:700; font-size:0.85rem; color:#64748b;">Outcome / Discussion Notes *</label>
                <textarea name="result_notes" rows="3" required placeholder="What happened during this follow-up?" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px; font-family:inherit; resize:vertical;"></textarea>
            </div>
            
            <div style="margin-bottom: 20px; padding-bottom:15px; border-bottom:1px dashed #e2e8f0;">
                <label style="display:block; margin-bottom:6px; font-weight:700; font-size:0.85rem; color:#64748b;">Update Lead Stage (Optional)</label>
                <select name="new_status_id" style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px; background:#f8fafc; font-family:inherit;">
                    <option value="">-- Keep Current status --</option>
                    <?php foreach($all_statuses as $st): ?>
                        <option value="<?= $st['id'] ?>"><?= 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 style="display:block; margin-bottom:6px; font-weight:700; font-size:0.85rem; color:#64748b;">Next Date</label>
                    <input type="date" name="next_date" style="width:100%; padding:9px; border:1px solid #e2e8f0; border-radius:8px; font-family:inherit;">
                </div>
                <div>
                    <label style="display:block; margin-bottom:6px; font-weight:700; font-size:0.85rem; color:#64748b;">Next Time</label>
                    <input type="time" name="next_time" value="10:00" style="width:100%; padding:9px; border:1px solid #e2e8f0; border-radius:8px; font-family:inherit;">
                </div>
                <div style="grid-column: 1/-1;">
                    <label style="display:block; margin-bottom:6px; font-weight:700; font-size:0.85rem; color:#64748b;">Next Follow-up Notes</label>
                    <input type="text" name="next_notes" placeholder="Plan for the next step..." style="width:100%; padding:9px; border:1px solid #e2e8f0; border-radius:8px; font-family:inherit;">
                </div>
            </div>
            
            <div style="display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" onclick="closeFupModal()" style="padding:10px 18px; background:#f1f5f9; color:#475569; border:none; border-radius:8px; font-weight:600; cursor:pointer;">Cancel</button>
                <button type="submit" name="complete_followup" style="padding:10px 18px; background:#10b981; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer;"><i class="fa-solid fa-check"></i> Save & Complete</button>
            </div>
        </form>
    </div>
</div>

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

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