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

// Get current month/year or use requested
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Handle constraints
if ($month < 1) { $month = 12; $year--; }
if ($month > 12) { $month = 1; $year++; }

// Calculate dates for calendar logic
$first_day_of_month = mktime(0, 0, 0, $month, 1, $year);
$days_in_month = (int)date('t', $first_day_of_month);
$month_name = date('F', $first_day_of_month);
$day_of_week = (int)date('w', $first_day_of_month); // 0 (Sun) to 6 (Sat)
$current_date = date('Y-m-d');

// Setup nav variables
$prev_month = $month - 1;
$prev_year = $year;
$next_month = $month + 1;
$next_year = $year;

// Fetch ALL meetings for this month
$start_date_str = sprintf('%04d-%02d-01', $year, $month);
$end_date_str = sprintf('%04d-%02d-%02d', $year, $month, $days_in_month);

$stmt = $pdo->prepare("
    SELECT m.*, l.name as lead_name 
    FROM meetings m
    LEFT JOIN leads l ON m.lead_id = l.id
    WHERE m.meeting_date >= ? AND m.meeting_date <= ?
    ORDER BY m.meeting_date ASC, m.start_time ASC
");
$stmt->execute([$start_date_str, $end_date_str]);
$month_meetings = $stmt->fetchAll();

// Group meetings by date (e.g., '2023-10-15' => [meeting1, meeting2])
$meetings_by_date = [];
foreach ($month_meetings as $m) {
    $meetings_by_date[$m['meeting_date']][] = $m;
}

// Map statuses to light background colors for calendar chips
function getStatusColor($status) {
    switch($status) {
        case 'scheduled': return '#e0f2fe; color: #0284c7; border:1px solid #bae6fd;';
        case 'completed': return '#d1fae5; color: #059669; border:1px solid #a7f3d0;';
        case 'rescheduled': return '#fef3c7; color: #d97706; border:1px solid #fde68a;';
        case 'cancelled': return '#fee2e2; color: #ef4444; border:1px solid #fecaca;';
        default: return '#f1f5f9; color: #475569; border:1px solid #e2e8f0;';
    }
}
?>

<div class="dashboard-content">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 15px;">
        <h2 style="font-size: 1.8rem; font-weight: 700; color: var(--dark); margin:0;">
            <i class="fa-regular fa-calendar-days" style="color: var(--primary);"></i> Calendar Dashboard
        </h2>
        <div>
            <a href="meeting_add_edit.php" style="display:inline-flex; align-items:center; padding: 10px 20px; background:var(--primary); color:white; border-radius:6px; text-decoration: none; font-weight: 600;"><i class="fa-solid fa-plus" style="margin-right:8px;"></i> Schedule Meeting</a>
            <a href="meetings.php" style="display:inline-flex; align-items:center; padding: 10px 20px; background:#e2e8f0; color:var(--dark); border-radius:6px; text-decoration: none; font-weight: 600; margin-left:10px;"><i class="fa-solid fa-list" style="margin-right:8px;"></i> List View</a>
        </div>
    </div>

    <!-- Calendar Wrapper -->
    <div class="data-card" style="background:#fff; border-radius:12px; border:1px solid var(--border); box-shadow:0 4px 15px rgba(0,0,0,0.03); overflow:hidden;">
        
        <!-- Header Controls -->
        <div style="padding: 20px 25px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background:#f8fafc;">
            <a href="calendar.php?month=<?= $prev_month ?>&year=<?= $prev_year ?>" style="padding: 8px 15px; background: #fff; border: 1px solid var(--border); border-radius: 6px; color: var(--dark); text-decoration:none; font-weight:600;"><i class="fa-solid fa-chevron-left"></i> Prev</a>
            
            <h3 style="margin: 0; font-size: 1.4rem; color: var(--dark);"><?= $month_name ?> <?= $year ?></h3>
            
            <div style="display:flex; gap:10px;">
                <a href="calendar.php" style="padding: 8px 15px; background: #e0f2fe; border: none; border-radius: 6px; color: var(--primary); text-decoration:none; font-weight:600;">Today</a>
                <a href="calendar.php?month=<?= $next_month ?>&year=<?= $next_year ?>" style="padding: 8px 15px; background: #fff; border: 1px solid var(--border); border-radius: 6px; color: var(--dark); text-decoration:none; font-weight:600;">Next <i class="fa-solid fa-chevron-right"></i></a>
            </div>
        </div>

        <!-- Desktop Calendar Grid -->
        <div class="calendar-grid">
            <!-- Day Headers -->
            <div class="cal-header">Sun</div>
            <div class="cal-header">Mon</div>
            <div class="cal-header">Tue</div>
            <div class="cal-header">Wed</div>
            <div class="cal-header">Thu</div>
            <div class="cal-header">Fri</div>
            <div class="cal-header">Sat</div>

            <!-- Empty slots before day 1 -->
            <?php for ($i = 0; $i < $day_of_week; $i++): ?>
                <div class="cal-cell cal-empty"></div>
            <?php endfor; ?>

            <!-- Days -->
            <?php 
            for ($day = 1; $day <= $days_in_month; $day++): 
                $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                $is_today = ($date_str === $current_date);
            ?>
                <div class="cal-cell <?= $is_today ? 'cal-today' : '' ?>">
                    <div class="cal-day-num"><?= $day ?></div>
                    
                    <div class="cal-events">
                        <?php if(isset($meetings_by_date[$date_str])): ?>
                            <?php foreach($meetings_by_date[$date_str] as $m): ?>
                                <a href="meeting_add_edit.php?edit=<?= $m['id'] ?>" class="cal-event-chip" style="background: <?= getStatusColor($m['status']) ?>" title="<?= htmlspecialchars($m['title']) ?> (<?= htmlspecialchars($m['lead_name'] ?? 'General') ?>)">
                                    <span class="evt-time"><?= date('g:ia', strtotime($m['start_time'])) ?></span>
                                    <span class="evt-title"><?= htmlspecialchars($m['title']) ?></span>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endfor; ?>

            <!-- Empty slots after last day to fill grid -->
            <?php 
            $total_days_rendered = $day_of_week + $days_in_month;
            $remaining_cells = (7 - ($total_days_rendered % 7)) % 7;
            for ($i = 0; $i < $remaining_cells; $i++):
            ?>
                <div class="cal-cell cal-empty"></div>
            <?php endfor; ?>

        </div>
    </div>
</div>

<style>
/* Custom Calendar CSS */
.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    background: var(--border);
    gap: 1px; /* Creates the inner borders automatically */
}
.cal-header {
    background: #f8fafc;
    padding: 15px 10px;
    text-align: center;
    font-weight: 700;
    color: #64748b;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.cal-cell {
    background: #fff;
    min-height: 120px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    transition: background 0.2s;
}
.cal-cell:hover {
    background: #f8fafc;
}
.cal-empty {
    background: #fcfcfc;
}
.cal-today {
    background: #f0f9ff;
}
.cal-day-num {
    font-weight: 700;
    color: var(--dark);
    font-size: 1.1rem;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    border-radius: 50%;
}
.cal-today .cal-day-num {
    background: var(--primary);
    color: #fff;
}
.cal-events {
    display: flex;
    flex-direction: column;
    gap: 5px;
    flex: 1;
    overflow-y: auto;
}
/* Hide scrollbar for clean look */
.cal-events::-webkit-scrollbar { width: 4px; }
.cal-events::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }

.cal-event-chip {
    display: block;
    padding: 4px 6px;
    border-radius: 4px;
    font-size: 0.75rem;
    text-decoration: none;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    transition: filter 0.2s;
}
.cal-event-chip:hover {
    filter: brightness(0.95);
}
.evt-time {
    font-weight: 700;
    margin-right: 3px;
    opacity: 0.8;
}
.evt-title {
    font-weight: 600;
}

/* Mobile Responsiveness */
@media (max-width: 900px) {
    .calendar-grid {
        display: flex;
        flex-direction: column;
        gap: 0;
    }
    .cal-header {
        display: none; /* Hide standard headers on mobile */
    }
    .cal-empty {
        display: none; /* Hide empty slots on mobile */
    }
    .cal-cell {
        min-height: auto;
        border-bottom: 1px solid var(--border);
        flex-direction: row;
        align-items: flex-start;
        padding: 15px;
    }
    .cal-day-num {
        margin-bottom: 0;
        margin-right: 15px;
        background: #f1f5f9;
    }
    .cal-events {
        flex-direction: row;
        flex-wrap: wrap;
    }
    .cal-event-chip {
        white-space: normal;
        margin-bottom: 5px;
    }
}
</style>

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