<?php
require_once 'includes/header.php';

// Handle Action (Delete, Mark Done, Cancel - GET)
if (isset($_GET['action']) && isset($_GET['id'])) {
    $f_id   = (int)$_GET['id'];
    $action = $_GET['action'];
    $valid_actions = ['completed', 'cancelled', 'delete'];
    
    if (in_array($action, $valid_actions)) {
        try {
            if ($action === 'delete') {
                // Security: Ensure the follow-up belongs to a lead assigned to this agent
                $stmt = $pdo->prepare("DELETE f FROM lead_followups f 
                                     JOIN leads l ON f.lead_id = l.id 
                                     WHERE f.id = ? AND l.assigned_agent_id = ?");
                $stmt->execute([$f_id, $agent_id]);
                $msg = "deleted";
            } else {
                $status = ($action === 'completed') ? 'completed' : 'cancelled';
                $stmt = $pdo->prepare("UPDATE lead_followups f 
                                     JOIN leads l ON f.lead_id = l.id 
                                     SET f.status = ?, f.completed_at = " . ($status==='completed' ? "NOW()" : "NULL") . " 
                                     WHERE f.id = ? AND l.assigned_agent_id = ?");
                $stmt->execute([$status, $f_id, $agent_id]);
                $msg = "updated";
            }
            $qs = array_diff_key($_GET, ['action'=>'','id'=>'']);
            header("Location: followups.php?" . http_build_query($qs) . "&msg=$msg");
            exit;
        } catch (PDOException $e) { $error = "Action Error: " . $e->getMessage(); }
    }
}

// Handle Detailed Follow-up Completion (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'] ?? '');
    
    // Security: Ensure this follow-up belongs to this agent's lead
    $fup_data = $pdo->prepare("SELECT f.lead_id FROM lead_followups f JOIN leads l ON f.lead_id = l.id WHERE f.id = ? AND l.assigned_agent_id = ?");
    $fup_data->execute([$f_id, $agent_id]);
    $f_lead = $fup_data->fetch();
    
    if ($f_lead) {
        $lead_id = $f_lead['lead_id'];
        try {
            $pdo->beginTransaction();
            // Append outcome to notes
            $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) {
                // Agent also has permission to change status for their lead
                $pdo->prepare("UPDATE leads SET status_id=? WHERE id=? AND assigned_agent_id=?")->execute([$new_status_id, $lead_id, $agent_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: followups.php?msg=updated");
            exit;
        } catch (PDOException $e) { $pdo->rollBack(); $error = "Error: " . $e->getMessage(); }
    }
}

// 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.assigned_agent_id = ? AND l.is_junk = 0";
$params = [$agent_id];

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 === 'completed')     { $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.completed_at 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 for tabs
$counts = $pdo->prepare("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.assigned_agent_id = ? AND l.is_junk=0");
$counts->execute([$agent_id]);
$counts = $counts->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 'followups.php?' . http_build_query($q);
}
?>

<script>document.getElementById('page-title').textContent='My Follow-Ups';</script>

<style>
.btn-3d { display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:8px; text-decoration:none; transition:all 0.1s ease; position:relative; top:0; border:none; cursor:pointer; margin-left:5px; }
.btn-3d-view   { background:#3b82f6; color:#fff; box-shadow:0 3px 0 #2563eb; }
.btn-3d-done   { background:#22c55e; color:#fff; box-shadow:0 3px 0 #16a34a; }
.btn-3d-cancel { background:#ef4444; color:#fff; box-shadow:0 3px 0 #dc2626; }
.btn-3d-del    { background:#64748b; color:#fff; box-shadow:0 3px 0 #475569; }
.btn-3d:active { top:3px; box-shadow:none !important; }

.fup-type-chip { display:inline-flex; align-items:center; gap:8px; padding:10px 18px; border-radius:25px; font-weight:700; font-size:0.85rem; text-decoration:none; border:2px solid #e2e8f0; background:#fff; color:#64748b; transition:all 0.2s; white-space:nowrap; }
.active-upcoming { background:#3b82f6; color:#fff; border-color:#3b82f6; box-shadow:0 4px 12px rgba(59,130,246,0.3); }
.active-missed   { background:#ef4444; color:#fff; border-color:#ef4444; box-shadow:0 4px 12px rgba(239,68,68,0.3); }
.active-done     { background:#22c55e; color:#fff; border-color:#22c55e; box-shadow:0 4px 12px rgba(34,197,94,0.3); }
.active-cancelled{ background:#94a3b8; color:#fff; border-color:#94a3b8; box-shadow:0 4px 12px rgba(148,163,184,0.3); }
.f-count { background:rgba(255,255,255,0.25); padding:1px 8px; border-radius:12px; font-size:0.75rem; }
.fup-type-chip:not([class*="active"]) .f-count { background:#f1f5f9; color:#64748b; }

.date-pill { padding:7px 16px; border-radius:20px; font-size:0.82rem; font-weight:700; 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); }

@media (max-width: 768px) {
    /* Force compact ROW view — override any global transforms or default overflows */
    .ag-table, .ag-table thead, .ag-table tbody,
    .ag-table th, .ag-table td, .ag-table tr {
        display: revert !important;
    }
    .ag-table { width:100%; border-collapse:collapse; display: table !important; }
    .ag-table thead tr { position: relative !important; top: auto !important; left: auto !important; }
    .ag-table th, .ag-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;
    }
    .ag-table tr {
        border: none !important;
        border-radius: 0 !important;
        margin-bottom: 0 !important;
        padding: 0 !important;
        box-shadow: none !important;
        display: table-row !important;
    }
    .ag-table td:before { display: none !important; content: none !important; }
    
    /* Hide non-essential columns on mobile to keep it compact */
    .ag-table th:nth-child(3), .ag-table td:nth-child(3), /* Scheduled For */
    .ag-table th:nth-child(4), .ag-table td:nth-child(4), /* Notes */
    .ag-table th:nth-child(5), .ag-table td:nth-child(5)  /* Status */
    { display: none !important; }

    .btn-3d { width: 30px !important; height: 30px !important; font-size: 0.8rem !important; margin-left: 4px !important; }
}
</style>

<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;background:linear-gradient(135deg, #18aadf, #0369a1);color:#fff;border:none;">
    <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;">
        <div>
            <h2 style="font-size:1.4rem;font-weight:800;margin-bottom:4px;"><i class="fa-solid fa-bell"></i> My Follow-ups</h2>
            <p style="font-size:0.85rem;opacity:0.9;">Manage your daily sales interactions and follow-up tasks.</p>
        </div>
        <div style="background:rgba(255,255,255,0.1);padding:10px 20px;border-radius:12px;text-align:center;border:1px solid rgba(255,255,255,0.15);">
            <div style="font-size:1.6rem;font-weight:800;"><?=array_sum([$counts['upcoming']??0, $counts['missed']??0])?></div>
            <div style="font-size:0.75rem;opacity:0.8;font-weight:700;">Remaining</div>
        </div>
    </div>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert-success">Follow-up <?=$_GET['msg']==='deleted'?'deleted':'updated'?> successfully.</div>
<?php endif; ?>

<!-- Tabs -->
<div style="display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap;">
    <?php $tabs = [
        ['upcoming',  'Upcoming', $counts['upcoming'] ?? 0, 'fa-clock'],
        ['missed',    'Missed',   $counts['missed']   ?? 0, 'fa-triangle-exclamation'],
        ['done',      'Done',     $counts['done']     ?? 0, 'fa-circle-check'],
        ['cancelled', 'Cancelled',$counts['cancelled']?? 0, 'fa-ban'],
    ];
    foreach($tabs as [$type, $label, $count, $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="f-count"><?=$count?></span>
    </a>
    <?php endforeach; ?>
</div>

<!-- Date Filters -->
<div class="ag-card" style="padding:14px 20px;margin-bottom:20px;">
    <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
        <span style="font-size:0.8rem;font-weight:700;color:#94a3b8;text-transform:uppercase;">Quick Filter:</span>
        <div style="display:flex;gap:6px;flex-wrap:wrap;">
            <?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; ?>
        </div>
        <form method="GET" style="display:inline-flex;gap:6px;align-items:center;">
            <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="width:auto;padding:5px 10px;font-size:0.8rem;border-radius:20px;">
            <span style="color:#94a3b8;">-</span>
            <input type="date" name="date_to" value="<?=htmlspecialchars($f_to)?>" style="width:auto;padding:5px 10px;font-size:0.8rem;border-radius:20px;">
            <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>
</div>

<div class="ag-card" style="padding:0;overflow:hidden;">
    <div style="overflow-x:auto;">
        <table class="ag-table">
            <thead>
                <tr>
                    <th style="width:60px;padding-left:22px;">S.No</th>
                    <th>Lead / Contact</th>
                    <th>Scheduled For</th>
                    <th>Notes</th>
                    <th>Status</th>
                    <th style="text-align:right;padding-right:22px;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($followups)): ?>
                <tr><td colspan="6" style="text-align:center;padding:50px;color:#94a3b8;"><i class="fa-regular fa-calendar-check" style="font-size:2.5rem;display:block;margin-bottom:12px;color:#e2e8f0;"></i>No <?=$f_type?> follow-ups found.</td></tr>
            <?php else: $sno=1; foreach ($followups as $f): 
                $f_dt = strtotime($f['followup_date']);
                $diff = $f_dt - time();
                $is_missed = ($f['status']==='pending' && $diff < 0);
            ?>
                <tr style="<?=$is_missed?'background:#fff8f8;':''?>">
                    <td style="padding-left:22px;color:#94a3b8;font-weight:700;">#<?=$sno++?></td>
                    <td>
                        <div style="font-weight:800;color:var(--dark);font-size:0.95rem;"><?=htmlspecialchars($f['lead_phone'])?></div>
                        <?php if($f['lead_name']): ?><div style="font-size:0.75rem;color:#94a3b8;font-weight:600;"><?=htmlspecialchars($f['lead_name'])?></div><?php endif; ?>
                    </td>
                    <td>
                        <div style="font-weight:700;font-size:0.85rem;color:#475569;"><?=date('d M, Y', $f_dt)?></div>
                        <div style="font-size:0.75rem;color:#94a3b8;"><?=date('h:i A', $f_dt)?></div>
                    </td>
                    <td style="font-size:0.82rem;color:#64748b;max-width:260px;"><?=htmlspecialchars($f['notes'] ?: '—')?></td>
                    <td>
                        <?php
                        $b_color = '#fef3c7'; $t_color = '#d97706'; $text = 'Pending';
                        if($f['status']==='completed') { $b_color = '#dcfce7'; $t_color = '#16a34a'; $text = 'Completed'; }
                        elseif($f['status']==='cancelled') { $b_color = '#f1f5f9'; $t_color = '#64748b'; $text = 'Cancelled'; }
                        elseif($is_missed) { $b_color = '#fee2e2'; $t_color = '#ef4444'; $text = 'Missed'; }
                        ?>
                        <span style="background:<?=$b_color?>;color:<?=$t_color?>;padding:3px 10px;border-radius:8px;font-size:0.7rem;font-weight:800;text-transform:uppercase;letter-spacing:0.04em;">
                            <?=$text?>
                        </span>
                    </td>
                    <td style="text-align:right;padding-right:22px;">
                        <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="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-ban"></i></a>
                        <?php endif; ?>
                        <a href="followups.php?action=delete&id=<?=$f['id']?>&type=<?=$f_type?>&period=<?=$f_period?>" class="btn-3d btn-3d-del" title="Delete" onclick="return confirm('Permanently delete?')"><i class="fa-solid fa-trash"></i></a>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </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="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'; ?>
