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

// Handle Action (Delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && !empty($_POST['selected_meetings'])) {
    $action = $_POST['bulk_action'];
    $ids = array_map('intval', $_POST['selected_meetings']);
    $ids_string = implode(',', $ids);
    
    try {
        if ($action === 'delete') {
             // Security: Ensure meetings belong to this agent's leads or are assigned to this agent
             $pdo->query("DELETE FROM meetings WHERE id IN ($ids_string) AND agent_id = $agent_id");
             header("Location: meetings.php?msg=bulk_deleted");
             exit;
        }
    } catch (PDOException $e) {
        $error = "Bulk Error: " . $e->getMessage();
    }
}

if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $action = $_GET['action'];

    try {
        if ($action === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM meetings WHERE id = ? AND agent_id = ?");
            $stmt->execute([$id, $agent_id]);
            $msg = "deleted";
        } elseif (in_array($action, ['scheduled', 'completed', 'cancelled', 'rescheduled'])) {
            $stmt = $pdo->prepare("UPDATE meetings SET status = ? WHERE id = ? AND agent_id = ?");
            $stmt->execute([$action, $id, $agent_id]);
            $msg = "status_updated";
        }
        header("Location: meetings.php?msg=$msg");
        exit;
    } catch (PDOException $e) { $error = "Error: " . $e->getMessage(); }
}

// Filters
$search = $_GET['search'] ?? '';
$filter_status = $_GET['status'] ?? '';
$filter_date = $_GET['date'] ?? '';

$sql = "
    SELECT m.*, l.name as lead_name, l.phone as lead_phone 
    FROM meetings m
    LEFT JOIN leads l ON m.lead_id = l.id
    WHERE m.agent_id = ?
";
$params = [$agent_id];

if (!empty($search)) {
    $sql .= " AND (m.title LIKE ? OR l.name LIKE ? OR l.phone LIKE ?)";
    $p = "%$search%"; $params[] = $p; $params[] = $p; $params[] = $p;
}
if (!empty($filter_status)) { $sql .= " AND m.status = ?"; $params[] = $filter_status; }
if (!empty($filter_date))   { $sql .= " AND m.meeting_date = ?"; $params[] = $filter_date; }

$sql .= " ORDER BY m.meeting_date DESC, m.start_time DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$meetings = $stmt->fetchAll();

function getStatusBadgeClass($status) {
    switch ($status) {
        case 'scheduled': return 'badge-pending';
        case 'completed': return 'badge-completed';
        case 'cancelled': return 'badge-danger';
        case 'rescheduled': return 'badge-warning';
        default: return 'badge-pending';
    }
}
?>

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

<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;background:linear-gradient(135deg, var(--primary), #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-handshake"></i> My Meetings</h2>
            <p style="font-size:0.85rem;opacity:0.9;">Manage your scheduled appointments and site visits.</p>
        </div>
    </div>
</div>

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

<!-- Filter Bar -->
<div class="ag-card" style="padding:18px 22px;margin-bottom:20px;">
    <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
        <div style="flex:2;min-width:180px;">
            <label>Search</label>
            <input type="text" name="search" value="<?=htmlspecialchars($search)?>" placeholder="Title, Lead Name or Phone">
        </div>
        <div style="flex:1;min-width:130px;">
            <label>Status</label>
            <select name="status">
                <option value="">All Status</option>
                <option value="scheduled" <?=$filter_status=='scheduled'?'selected':''?>>Scheduled</option>
                <option value="completed" <?=$filter_status=='completed'?'selected':''?>>Completed</option>
                <option value="cancelled" <?=$filter_status=='cancelled'?'selected':''?>>Cancelled</option>
            </select>
        </div>
        <div style="flex:1;min-width:130px;">
            <label>Date</label>
            <input type="date" name="date" value="<?=htmlspecialchars($filter_date)?>">
        </div>
        <div style="display:flex;gap:8px;">
            <button type="submit" class="btn-primary"><i class="fa-solid fa-filter"></i> Filter</button>
            <?php if(!empty($search)||!empty($filter_status)||!empty($filter_date)): ?><a href="meetings.php" class="btn-primary" style="background:#f1f5f9;color:#64748b;"><i class="fa-solid fa-xmark"></i> Clear</a><?php endif; ?>
        </div>
    </form>
</div>

<div class="ag-card" style="padding:0;overflow:hidden;">
    <form action="meetings.php" method="POST">
        <div style="padding:16px 22px;border-bottom:2px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
            <label style="display:flex;align-items:center;cursor:pointer;font-weight:700;font-size:0.9rem;gap:10px;">
                <input type="checkbox" id="selectAll" style="width:17px;height:17px;accent-color:var(--primary);">
                Select All Meetings
            </label>
            <button type="submit" name="bulk_action" value="delete" class="btn-primary" style="background:#fee2e2;color:#ef4444;border:none;padding:7px 14px;font-size:0.8rem;" onclick="return confirm('Delete selected meetings?')">
                <i class="fa-solid fa-trash"></i> Bulk Delete
            </button>
        </div>

        <div style="overflow-x:auto;">
            <table class="ag-table">
                <thead>
                    <tr>
                        <th style="width:40px;"></th>
                        <th>Meeting Details</th>
                        <th>Lead / Contact</th>
                        <th>Date & Time</th>
                        <th>Status</th>
                        <th style="text-align:right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($meetings)): ?>
                    <tr><td colspan="6" style="text-align:center;padding:40px;color:#94a3b8;"><i class="fa-solid fa-calendar-xmark" style="font-size:2rem;display:block;margin-bottom:10px;color:#e2e8f0;"></i>No meetings found.</td></tr>
                <?php else: foreach ($meetings as $m): 
                    $type_icon = ($m['meeting_type']==='online_meeting') ? 'fa-video' : (($m['meeting_type']==='site_visit') ? 'fa-helmet-safety' : 'fa-users');
                    $type_color = ($m['meeting_type']==='online_meeting') ? '#8b5cf6' : (($m['meeting_type']==='site_visit') ? '#f59e0b' : '#3b82f6');
                ?>
                    <tr>
                        <td><input type="checkbox" name="selected_meetings[]" value="<?=$m['id']?>" class="meeting-checkbox" style="width:16px;height:16px;"></td>
                        <td>
                            <div style="font-weight:700;color:#1e293b;"><?=htmlspecialchars($m['title'])?></div>
                            <div style="display:flex;align-items:center;gap:6px;margin-top:4px;">
                                <span style="font-size:0.7rem;font-weight:700;background:<?=$type_color?>20;color:<?=$type_color?>;padding:2px 8px;border-radius:10px;display:inline-flex;align-items:center;gap:4px;">
                                    <i class="fa-solid <?=$type_icon?>"></i> <?=ucwords(str_replace('_',' ',$m['meeting_type']))?>
                                </span>
                                <?php if($m['location']): ?><span style="font-size:0.75rem;color:#94a3b8;"><i class="fa-solid fa-location-dot"></i> <?=htmlspecialchars($m['location'])?></span><?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <?php if($m['lead_name']): ?>
                                <div style="font-weight:700;color:var(--primary);"><?=htmlspecialchars($m['lead_name'])?></div>
                                <div style="font-size:0.78rem;color:#94a3b8;"><?=htmlspecialchars($m['lead_phone'])?></div>
                            <?php else: ?>
                                <span style="font-size:0.8rem;color:#94a3b8;font-style:italic;">General</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div style="font-weight:600;font-size:0.85rem;color:#475569;"><?=date('d M, Y', strtotime($m['meeting_date']))?></div>
                            <div style="font-size:0.78rem;color:#94a3b8;"><?=date('h:i A', strtotime($m['start_time']))?> - <?=date('h:i A', strtotime($m['end_time']))?></div>
                        </td>
                        <td>
                            <span style="display:inline-block;padding:3px 10px;border-radius:10px;font-size:0.72rem;font-weight:700;background:<?=($m['status']==='completed')?'#dcfce7':(($m['status']==='cancelled'?'#fee2e2':'#fef3c7'))?>;color:<?=($m['status']==='completed')?'#16a34a':(($m['status']==='cancelled'?'#ef4444':'#d97706'))?>;">
                                <?=ucfirst($m['status'])?>
                            </span>
                        </td>
                        <td style="text-align:right;">
                            <?php if($m['status']==='scheduled'): ?>
                                <a href="meetings.php?action=completed&id=<?=$m['id']?>" style="color:#16a34a;background:#dcfce7;width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border-radius:6px;text-decoration:none;" title="Mark Completed"><i class="fa-solid fa-check"></i></a>
                            <?php endif; ?>
                            <a href="meetings.php?action=delete&id=<?=$m['id']?>" style="color:#ef4444;background:#fee2e2;width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border-radius:6px;text-decoration:none;" title="Delete" onclick="return confirm('Delete this meeting?')"><i class="fa-solid fa-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </form>
</div>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.meeting-checkbox').forEach(cb => cb.checked = this.checked);
});
</script>

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