<?php
require_once 'config/db.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') {
             $pdo->query("DELETE FROM meetings WHERE id IN ($ids_string)");
             $msg = "bulk_deleted";
             header("Location: meetings.php?msg=$msg");
             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 = ?");
            $stmt->execute([$id]);
            $msg = "deleted";
        } elseif (in_array($action, ['scheduled', 'completed', 'cancelled', 'rescheduled'])) {
            $stmt = $pdo->prepare("UPDATE meetings SET status = ? WHERE id = ?");
            $stmt->execute([$action, $id]);
            $msg = "status_updated";
        }
        header("Location: meetings.php?msg=$msg");
        exit;
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

if (isset($_GET['msg'])) {
    if ($_GET['msg'] === 'deleted' || $_GET['msg'] === 'bulk_deleted') {
        $success = "Meeting(s) successfully deleted.";
    } elseif ($_GET['msg'] === 'status_updated') {
        $success = "Meeting status updated.";
    }
}

// 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 1=1
";
$params = [];

if (!empty($search)) {
    $sql .= " AND (m.title LIKE ? OR l.name LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
}

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 ASC, m.start_time ASC";
$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';
    }
}

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <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-solid fa-list-check"></i> All Meetings</h2>
            <p>View and manage all your scheduled appointments.</p>
        </div>
        <a href="meeting_add_edit.php" style="color:var(--primary); background:#fff; display:inline-flex; align-items:center; justify-content:center; padding: 10px 20px; border-radius:6px; text-decoration: none; font-weight: 600;"><i class="fa-solid fa-plus" style="margin-right: 8px;"></i> Schedule Meeting</a>
    </div>

    <?php if (isset($success)): ?>
        <div 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 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; ?>

    <!-- Filter Bar -->
    <div class="data-card" style="margin-bottom: 20px; background:#fff; padding: 20px; border-radius:12px; box-shadow:0 4px 15px rgba(0,0,0,0.03);">
        <form action="meetings.php" method="GET" style="display: flex; gap: 15px; flex-wrap: wrap; align-items: flex-end;">
            <div style="flex: 1; min-width: 200px;">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem; color:#64748b;">Search</label>
                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Meeting Title or Lead Name" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px;">
            </div>
            
            <div style="flex: 1; min-width: 150px;">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem; color:#64748b;">Date</label>
                <input type="date" name="date" value="<?= htmlspecialchars($filter_date) ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
            </div>

            <div style="flex: 1; min-width: 150px;">
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem; color:#64748b;">Status</label>
                <select name="status" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">All Statuses</option>
                    <option value="scheduled" <?= $filter_status == 'scheduled' ? 'selected' : '' ?>>Scheduled</option>
                    <option value="completed" <?= $filter_status == 'completed' ? 'selected' : '' ?>>Completed</option>
                    <option value="rescheduled" <?= $filter_status == 'rescheduled' ? 'selected' : '' ?>>Rescheduled</option>
                    <option value="cancelled" <?= $filter_status == 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                </select>
            </div>
            
            <div>
                <button type="submit" style="padding:10px 20px; background:var(--dark); color:var(--white); border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-solid fa-magnifying-glass"></i> Filter</button>
                <?php if(!empty($search) || !empty($filter_status) || !empty($filter_date)): ?>
                    <a href="meetings.php" style="margin-left:5px; padding:10px 20px; background:#e2e8f0; color:var(--dark); text-decoration:none; border-radius:6px; font-weight:600; display:inline-block;">Reset</a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Meetings Table -->
    <style>
        .custom-checkbox { width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary); }
        .badge-danger { background-color: #fee2e2; color: #ef4444; border: 1px solid #fca5a5; }
        .badge-warning { background-color: #fef3c7; color: #f59e0b; border: 1px solid #fcd34d; }

        @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; }
            
            /* Hide non-essential columns on mobile */
            .admin-table th:nth-child(4), .admin-table td:nth-child(4), /* Date & Time */
            .admin-table th:nth-child(5), .admin-table td:nth-child(5)  /* Status */
            { display: none !important; }

            .dashboard-content { padding: 10px !important; }
        }
    </style>
    <div class="recent-activity" style="padding: 0;">
        <form action="meetings.php" method="POST" id="bulkForm">
            <div style="padding: 15px 20px; background: #f8fafc; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; border-top-left-radius: 12px; border-top-right-radius: 12px;">
                <label style="display: flex; align-items: center; cursor: pointer; font-weight: 600; color: var(--dark); font-size: 0.95rem;">
                    <input type="checkbox" id="selectAll" class="custom-checkbox" style="margin-right: 12px;"> Select All
                </label>
                <button type="submit" name="bulk_action" value="delete" style="padding: 6px 15px; background: #fee2e2; color: #ef4444; border: 1px solid #fca5a5; border-radius: 6px; font-weight: 600; font-size: 0.85rem; cursor: pointer;" title="Delete Selected" onclick="return confirm('Permanently delete selected meetings?');">
                    <i class="fa-solid fa-trash" style="margin-right: 6px;"></i> Bulk Delete
                </button>
            </div>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="padding-left: 20px; width: 40px;"></th>
                            <th>Meeting Details</th>
                            <th>Lead / Contact</th>
                            <th>Date & Time</th>
                            <th>Status</th>
                            <th style="padding-right: 20px; text-align: right;">Options</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($meetings) > 0): ?>
                            <?php foreach ($meetings as $m): ?>
                                <tr>
                                    <td style="padding-left: 20px;">
                                        <input type="checkbox" name="selected_meetings[]" value="<?= $m['id'] ?>" class="custom-checkbox meeting-checkbox">
                                    </td>
                                    <td>
                                        <?php
                                        $type_info = [
                                            'live_meeting'   => ['fa-people-group', '#3b82f6', 'Live Meeting'],
                                            'site_visit'     => ['fa-hard-hat',     '#f59e0b', 'Site Visit'],
                                            'online_meeting' => ['fa-video',        '#8b5cf6', 'Online Meeting'],
                                        ];
                                        $ti = $type_info[$m['meeting_type']] ?? ['fa-calendar', '#94a3b8', ucfirst(str_replace('_',' ',$m['meeting_type']))];
                                        ?>
                                        <div style="font-weight:700; color:var(--dark); font-size:1.05rem; margin-bottom:4px;"><?= htmlspecialchars($m['title']) ?></div>
                                        <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
                                            <span style="background:<?= $ti[1] ?>18; color:<?= $ti[1] ?>; padding:3px 9px; border-radius:10px; font-size:0.75rem; font-weight:700; display:inline-flex; align-items:center; gap:4px;">
                                                <i class="fa-solid <?= $ti[0] ?>"></i> <?= $ti[2] ?>
                                            </span>
                                            <?php if($m['meeting_type'] === 'online_meeting' && !empty($m['meeting_link'])): ?>
                                                <a href="<?= htmlspecialchars($m['meeting_link']) ?>" target="_blank" style="background:#8b5cf6; color:#fff; padding:3px 10px; border-radius:10px; font-size:0.75rem; font-weight:700; text-decoration:none; display:inline-flex; align-items:center; gap:4px;">
                                                    <i class="fa-solid fa-video"></i> Join
                                                </a>
                                            <?php endif; ?>
                                            <?php if($m['location']): ?>
                                                <div style="font-size:0.82rem; color:#64748b;"><i class="fa-solid fa-location-dot" style="margin-right:3px;"></i><?= htmlspecialchars($m['location']) ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <?php if($m['lead_name']): ?>
                                            <div style="font-weight:600; color:var(--primary);"><?= htmlspecialchars($m['lead_name']) ?></div>
                                            <div style="font-size:0.85rem; margin-top:2px;"><i class="fa-solid fa-phone" style="color:#94a3b8; font-size:0.8rem; margin-right:3px;"></i> <?= htmlspecialchars($m['lead_phone']) ?></div>
                                        <?php else: ?>
                                            <span style="color:#94a3b8; font-style:italic;">General Meeting</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td>
                                        <div style="font-weight:600; color:var(--dark);"><i class="fa-regular fa-calendar" style="color:#94a3b8; margin-right:4px;"></i> <?= date('M d, Y', strtotime($m['meeting_date'])) ?></div>
                                        <div style="font-size:0.85rem; color:#64748b; margin-top:2px;">
                                            <i class="fa-regular fa-clock" style="color:#94a3b8; margin-right:4px;"></i> <?= date('h:i A', strtotime($m['start_time'])) ?> - <?= date('h:i A', strtotime($m['end_time'])) ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <span class="badge <?= getStatusBadgeClass($m['status']) ?>" style="text-transform: capitalize;">
                                            <?= htmlspecialchars($m['status']) ?>
                                        </span>
                                    </td>

                                    <td style="text-align: right; padding-right: 20px;">
                                        <?php if($m['status'] === 'scheduled' || $m['status'] === 'rescheduled'): ?>
                                            <a href="meetings.php?action=completed&id=<?= $m['id'] ?>" title="Mark Completed" style="color:#10b981; display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; background:#d1fae5; border-radius:6px; margin-right:4px;"><i class="fa-solid fa-check"></i></a>
                                        <?php endif; ?>
                                        <a href="meeting_add_edit.php?edit=<?= $m['id'] ?>" title="Edit Meeting" style="color:var(--primary); display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; background:#e0f2fe; border-radius:6px; margin-right:4px;"><i class="fa-solid fa-pen"></i></a>
                                        <a href="meetings.php?action=delete&id=<?= $m['id'] ?>" title="Delete" onclick="return confirm('Permanently delete this meeting?');" style="color:var(--danger); display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; background:#fee2e2; border-radius:6px;"><i class="fa-solid fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" 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 meetings found. Click "Schedule Meeting" to create one.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>
</div>

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

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