<?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 agent 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.agent_id = ? AND m.meeting_date >= ? AND m.meeting_date <= ?
    ORDER BY m.meeting_date ASC, m.start_time ASC
");
$stmt->execute([$agent_id, $start_date_str, $end_date_str]);
$month_meetings = $stmt->fetchAll();

$meetings_by_date = [];
foreach ($month_meetings as $m) {
    $meetings_by_date[$m['meeting_date']][] = $m;
}

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 'cancelled': return '#fee2e2; color: #ef4444; border:1px solid #fca5a5;';
        default: return '#f1f5f9; color: #475569; border:1px solid #e2e8f0;';
    }
}
?>

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

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:15px;">
    <h2 style="font-size:1.5rem;font-weight:800;color:#0f172a;"><i class="fa-regular fa-calendar-days" style="color:var(--primary);"></i> My Calendar</h2>
    <a href="meetings.php" class="btn-primary" style="background:#f1f5f9;color:#64748b;"><i class="fa-solid fa-list"></i> List View</a>
</div>

<div class="ag-card" style="padding:0;overflow:hidden;border:none;box-shadow:0 10px 30px rgba(0,0,0,0.05);">
    <div style="padding:20px 25px;border-bottom:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center;background:#fff;">
        <a href="calendar.php?month=<?=$prev_month?>&year=<?=$prev_year?>" style="text-decoration:none;color:#64748b;font-weight:700;"><i class="fa-solid fa-chevron-left"></i> Prev</a>
        <h3 style="margin:0;font-size:1.3rem;font-weight:800;color:#0f172a;"><?=$month_name?> <?=$year?></h3>
        <a href="calendar.php?month=<?=$next_month?>&year=<?=$next_year?>" style="text-decoration:none;color:#64748b;font-weight:700;">Next <i class="fa-solid fa-chevron-right"></i></a>
    </div>

    <div style="display:grid;grid-template-columns:repeat(7, 1fr);background:#f1f5f9;gap:1px;">
        <?php foreach(['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] as $d): ?>
            <div style="background:#fff;padding:12px;text-align:center;font-weight:800;font-size:0.75rem;color:#94a3b8;text-transform:uppercase;letter-spacing:0.05em;"><?=$d?></div>
        <?php endforeach; ?>

        <?php for($i=0;$i<$day_of_week;$i++): ?><div style="background:#fbfcfd;min-height:110px;"></div><?php endfor; ?>

        <?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 style="background:#fff;min-height:110px;padding:8px;position:relative;border:1px solid transparent;transition:all 0.2s;<?=$is_today?'background:#f0f9ff;':''?>">
                <div style="font-weight:800;font-size:0.95rem;color:<?=$is_today?'var(--primary)':'#64748b'?>;margin-bottom:8px;display:flex;align-items:center;justify-content:center;width:24px;height:24px;<?=$is_today?'background:var(--primary);color:#fff;border-radius:6px;':''?>"><?=$day?></div>
                <div style="display:flex;flex-direction:column;gap:4px;">
                    <?php if(isset($meetings_by_date[$date_str])): foreach($meetings_by_date[$date_str] as $m): ?>
                        <div style="padding:4px 6px;border-radius:6px;font-size:0.7rem;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;<?=getStatusColor($m['status'])?>" title="<?=htmlspecialchars($m['title'])?>">
                            <?=date('h:iA', strtotime($m['start_time']))?> <?=htmlspecialchars($m['title'])?>
                        </div>
                    <?php endforeach; endif; ?>
                </div>
            </div>
        <?php endfor; ?>
        
        <?php 
        $total_rendered = $day_of_week + $days_in_month;
        $remain = (7 - ($total_rendered % 7)) % 7;
        for($i=0;$i<$remain;$i++): ?><div style="background:#fbfcfd;min-height:110px;"></div><?php endfor; ?>
    </div>
</div>

<style>
@media (max-width: 768px) {
    div[style*="grid-template-columns:repeat(7, 1fr)"] { grid-template-columns: 1fr !important; }
    div[style*="min-height:110px"] { min-height: auto !important; border-bottom: 1px solid #f1f5f9 !important; display: flex !important; align-items: flex-start !important; gap: 15px !important; padding: 15px !important; }
    div[style*="font-weight:800;font-size:0.75rem"] { display: none !important; }
    div[style*="background:#fbfcfd"] { display: none !important; }
}
</style>

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