<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/database.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/auth.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/functions.php';
requireRole('director', 'accountant', 'manager', 'production');

$pdo  = getDBConnection();
$user = currentUser();

// ── Tham số lọc ──────────────────────────────────────────────────────────
$viewMonth  = (int)($_GET['month']   ?? date('m'));
$viewYear   = (int)($_GET['year']    ?? date('Y'));
$filterDept = (int)($_GET['dept']    ?? 0);
$filterUser = (int)($_GET['user_id'] ?? 0);
$viewMode   = $_GET['view']          ?? 'month'; // month | day

if ($viewMonth < 1)  { $viewMonth = 12; $viewYear--; }
if ($viewMonth > 12) { $viewMonth = 1;  $viewYear++; }

$viewDay    = (int)($_GET['day'] ?? date('j'));
$daysInMon  = cal_days_in_month(CAL_GREGORIAN, $viewMonth, $viewYear);
if ($viewDay < 1 || $viewDay > $daysInMon) $viewDay = (int)date('j');

// ── Lấy danh sách nhân viên ───────────────────────────────────────────────
$empSQL = "SELECT u.id, u.full_name, u.employee_code, d.name AS dept_name, d.id AS dept_id,
                  r.display_name AS role_name,
                  ws.shift_name, ws.color AS shift_color,
                  ws.start_time AS shift_start, ws.end_time AS shift_end,
                  ws.work_hours AS shift_work_hours, ws.late_threshold
           FROM users u
           LEFT JOIN departments d ON u.department_id = d.id
           LEFT JOIN roles r ON u.role_id = r.id
           LEFT JOIN employee_shifts es ON es.user_id = u.id
               AND es.effective_date <= LAST_DAY(?)
               AND (es.end_date IS NULL OR es.end_date >= ?)
           LEFT JOIN work_shifts ws ON es.shift_id = ws.id
           WHERE u.is_active = 1 AND r.name != 'director'";
$empParams = ["$viewYear-$viewMonth-01", "$viewYear-$viewMonth-01"];

if ($filterDept) { $empSQL .= " AND u.department_id = ?"; $empParams[] = $filterDept; }
if ($filterUser) { $empSQL .= " AND u.id = ?";            $empParams[] = $filterUser; }
$empSQL .= " ORDER BY d.name, u.full_name";

$empStmt = $pdo->prepare($empSQL);
$empStmt->execute($empParams);
$employees = $empStmt->fetchAll();

// ── Lấy dữ liệu chấm công cả tháng ──────────────────────────────────────
$attStmt = $pdo->prepare("
    SELECT al.user_id, al.work_date, al.check_in, al.check_out,
           al.work_hours, al.is_late, al.late_minutes, al.source,
           al.early_leave, al.early_leave_minutes
    FROM attendance_logs al
    WHERE MONTH(al.work_date) = ? AND YEAR(al.work_date) = ?
    ORDER BY al.work_date
");
$attStmt->execute([$viewMonth, $viewYear]);
$attMap = [];
foreach ($attStmt->fetchAll() as $a) {
    $attMap[$a['user_id']][$a['work_date']] = $a;
}

// ── Lấy nghỉ phép đã duyệt ───────────────────────────────────────────────
$leaveStmt = $pdo->prepare("
    SELECT user_id, start_date, end_date, leave_type
    FROM leave_requests
    WHERE status = 'approved'
      AND ((MONTH(start_date)=? AND YEAR(start_date)=?)
        OR (MONTH(end_date)=?   AND YEAR(end_date)=?))
");
$leaveStmt->execute([$viewMonth, $viewYear, $viewMonth, $viewYear]);
$leaveMap = [];
foreach ($leaveStmt->fetchAll() as $lv) {
    $s = strtotime($lv['start_date']);
    $e = strtotime($lv['end_date']);
    for ($d = $s; $d <= $e; $d += 86400) {
        $leaveMap[$lv['user_id']][date('Y-m-d', $d)] = $lv['leave_type'];
    }
}

// ── Lấy OT đã duyệt ──────────────────────────────────────────────────────
$otStmt = $pdo->prepare("
    SELECT user_id, ot_date, hours, ot_type
    FROM overtime_requests
    WHERE status = 'approved'
      AND MONTH(ot_date) = ? AND YEAR(ot_date) = ?
");
$otStmt->execute([$viewMonth, $viewYear]);
$otMap = [];
foreach ($otStmt->fetchAll() as $ot) {
    $otMap[$ot['user_id']][$ot['ot_date']] = $ot;
}

// ── Lấy ngày lễ ──────────────────────────────────────────────────────────
$holidays = $pdo->prepare("SELECT holiday_date FROM holidays WHERE MONTH(holiday_date)=? AND YEAR(holiday_date)=?");
$holidays->execute([$viewMonth, $viewYear]);
$holidayDates = array_column($holidays->fetchAll(), 'holiday_date');

// ── Tính thống kê từng nhân viên ──────────────────────────────────────────
function calcStats($userId, $attMap, $leaveMap, $otMap, $viewMonth, $viewYear, $daysInMon, $holidayDates) {
    $stats = [
        'work_days'     => 0,  // Ngày có mặt
        'absent_days'   => 0,  // Vắng không phép
        'leave_days'    => 0,  // Nghỉ phép
        'late_count'    => 0,  // Số lần trễ
        'late_minutes'  => 0,  // Tổng phút trễ
        'early_count'   => 0,  // Về sớm
        'total_hours'   => 0,  // Tổng giờ làm
        'ot_hours'      => 0,  // Tổng giờ OT
        'ot_weekday'    => 0,
        'ot_weekend'    => 0,
        'ot_holiday'    => 0,
        'sunday_work'   => 0,  // Làm Chủ nhật
    ];

    for ($d = 1; $d <= $daysInMon; $d++) {
        $dateStr  = sprintf('%04d-%02d-%02d', $viewYear, $viewMonth, $d);
        $dow      = date('N', strtotime($dateStr)); // 1=Mon...7=Sun
        $isSun    = ($dow == 7);
        $isFuture = ($dateStr > date('Y-m-d'));
        if ($isFuture) continue;

        $att   = $attMap[$userId][$dateStr]  ?? null;
        $leave = $leaveMap[$userId][$dateStr] ?? null;
        $ot    = $otMap[$userId][$dateStr]    ?? null;

        // OT
        if ($ot) {
            $stats['ot_hours'] += $ot['hours'];
            if ($ot['ot_type'] === 'holiday')      $stats['ot_holiday'] += $ot['hours'];
            elseif ($ot['ot_type'] === 'weekend')  $stats['ot_weekend'] += $ot['hours'];
            else                                   $stats['ot_weekday'] += $ot['hours'];
        }

        if ($isSun) {
            if ($att && $att['check_in']) $stats['sunday_work']++;
            continue;
        }

        if ($leave && !$att) {
            $stats['leave_days']++;
        } elseif ($att && $att['check_in']) {
            $stats['work_days']++;
            $stats['total_hours'] += $att['work_hours'];
            if ($att['is_late'])       { $stats['late_count']++;  $stats['late_minutes'] += $att['late_minutes']; }
            if ($att['early_leave'])   { $stats['early_count']++; }
        } else {
            $stats['absent_days']++;
        }
    }
    return $stats;
}

// ── Dữ liệu cho dropdowns filter ─────────────────────────────────────────
$depts   = $pdo->query("SELECT * FROM departments ORDER BY name")->fetchAll();
$empList = $pdo->query("SELECT id, full_name, employee_code FROM users WHERE is_active=1 ORDER BY full_name")->fetchAll();

// ── Tổng hợp toàn công ty tháng này ──────────────────────────────────────
$summaryStmt = $pdo->prepare("
    SELECT
        COUNT(DISTINCT user_id)                                          AS total_checkins,
        SUM(is_late)                                                     AS total_late,
        ROUND(SUM(work_hours), 1)                                        AS total_hours,
        COUNT(CASE WHEN check_in IS NOT NULL AND check_out IS NULL THEN 1 END) AS missing_checkout
    FROM attendance_logs
    WHERE MONTH(work_date)=? AND YEAR(work_date)=?
");
$summaryStmt->execute([$viewMonth, $viewYear]);
$summary = $summaryStmt->fetch();

include $_SERVER['DOCUMENT_ROOT'] . '/erp/includes/header.php';
include $_SERVER['DOCUMENT_ROOT'] . '/erp/includes/sidebar.php';
?>

<div class="main-content">
<div class="container-fluid py-4">

    <!-- ── Tiêu đề ── -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="mb-1">📊 Bảng chấm công tổng hợp</h4>
            <p class="text-muted small mb-0">
                Tháng <?= $viewMonth ?>/<?= $viewYear ?> &bull; <?= count($employees) ?> nhân viên
            </p>
        </div>
        <div class="d-flex gap-2">
            <button onclick="exportExcel()" class="btn btn-success btn-sm">
                <i class="fas fa-file-excel me-1"></i>Xuất Excel
            </button>
            <button onclick="window.print()" class="btn btn-outline-secondary btn-sm">
                <i class="fas fa-print me-1"></i>In
            </button>
        </div>
    </div>

    <!-- ── Thống kê tổng quan ── -->
    <div class="row g-3 mb-4">
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="fs-2 fw-bold text-primary"><?= count($employees) ?></div>
                <div class="small text-muted">👥 Tổng nhân viên</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="fs-2 fw-bold text-success"><?= $summary['total_checkins'] ?? 0 ?></div>
                <div class="small text-muted">✅ NV đã chấm công</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="fs-2 fw-bold text-warning"><?= $summary['total_late'] ?? 0 ?></div>
                <div class="small text-muted">⚡ Lượt đi trễ</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="fs-2 fw-bold text-danger"><?= $summary['missing_checkout'] ?? 0 ?></div>
                <div class="small text-muted">⚠️ Thiếu giờ ra</div>
            </div>
        </div>
    </div>

    <!-- ── Bộ lọc ── -->
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body py-2">
            <form method="GET" class="row g-2 align-items-end">
                <input type="hidden" name="view" value="<?= htmlspecialchars($viewMode) ?>">

                <div class="col-6 col-md-2">
                    <label class="form-label small fw-semibold mb-1">Tháng</label>
                    <select name="month" class="form-select form-select-sm">
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                        <option value="<?= $m ?>" <?= $m == $viewMonth ? 'selected' : '' ?>>Tháng <?= $m ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="col-6 col-md-1">
                    <label class="form-label small fw-semibold mb-1">Năm</label>
                    <select name="year" class="form-select form-select-sm">
                        <?php for ($y = date('Y') - 1; $y <= date('Y') + 1; $y++): ?>
                        <option value="<?= $y ?>" <?= $y == $viewYear ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label small fw-semibold mb-1">Phòng ban</label>
                    <select name="dept" class="form-select form-select-sm">
                        <option value="">-- Tất cả --</option>
                        <?php foreach ($depts as $d): ?>
                        <option value="<?= $d['id'] ?>" <?= $filterDept == $d['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($d['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-6 col-md-3">
                    <label class="form-label small fw-semibold mb-1">Nhân viên</label>
                    <select name="user_id" class="form-select form-select-sm">
                        <option value="">-- Tất cả --</option>
                        <?php foreach ($empList as $e): ?>
                        <option value="<?= $e['id'] ?>" <?= $filterUser == $e['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($e['employee_code'] . ' - ' . $e['full_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 d-flex gap-1">
                    <button type="submit" class="btn btn-primary btn-sm flex-grow-1">
                        <i class="fas fa-search me-1"></i>Lọc
                    </button>
                    <a href="/erp/modules/attendance/all_attendance.php" class="btn btn-outline-secondary btn-sm">↺</a>
                </div>

                <!-- Chế độ xem -->
                <div class="col-md-2">
                    <label class="form-label small fw-semibold mb-1">Chế độ xem</label>
                    <div class="btn-group w-100">
                        <a href="?month=<?= $viewMonth ?>&year=<?= $viewYear ?>&dept=<?= $filterDept ?>&user_id=<?= $filterUser ?>&view=month"
                           class="btn btn-sm <?= $viewMode === 'month' ? 'btn-primary' : 'btn-outline-primary' ?>">
                            <i class="fas fa-calendar-alt"></i> Tháng
                        </a>
                        <a href="?month=<?= $viewMonth ?>&year=<?= $viewYear ?>&dept=<?= $filterDept ?>&user_id=<?= $filterUser ?>&view=summary"
                           class="btn btn-sm <?= $viewMode === 'summary' ? 'btn-primary' : 'btn-outline-primary' ?>">
                            <i class="fas fa-table"></i> Tổng hợp
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════
         CHẾ ĐỘ XEM: LỊCH THÁNG (mặc định)
    ══════════════════════════════════════════════ -->
    <?php if ($viewMode === 'month'): ?>

    <!-- Chú thích -->
    <div class="d-flex flex-wrap gap-2 mb-2">
        <?php
        $legends = [
            ['bg-success text-white',  '✓ Đúng giờ'],
            ['bg-warning text-dark',   '⚡ Đi trễ'],
            ['bg-info text-white',     '🏖️ Nghỉ phép'],
            ['bg-danger text-white',   '✗ Vắng'],
            ['bg-purple text-white',   '🌙 OT'],
            ['bg-light border',        '— Chủ nhật'],
        ];
        foreach ($legends as [$cls, $lbl]):
        ?>
        <span class="badge <?= $cls ?> px-2 py-1"><?= $lbl ?></span>
        <?php endforeach; ?>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-sm att-table mb-0" id="attTable">
                    <thead>
                        <!-- Hàng tháng + nút điều hướng -->
                        <tr class="table-dark">
                            <th class="sticky-col text-center" rowspan="2" style="min-width:170px; vertical-align:middle;">
                                <div class="d-flex align-items-center justify-content-center gap-1">
                                    <a href="?month=<?= $viewMonth-1 ?>&year=<?= $viewYear ?>&dept=<?= $filterDept ?>&user_id=<?= $filterUser ?>&view=month"
                                       class="btn btn-xs btn-outline-light"><i class="fas fa-chevron-left"></i></a>
                                    <span>T<?= $viewMonth ?>/<?= $viewYear ?></span>
                                    <a href="?month=<?= $viewMonth+1 ?>&year=<?= $viewYear ?>&dept=<?= $filterDept ?>&user_id=<?= $filterUser ?>&view=month"
                                       class="btn btn-xs btn-outline-light"><i class="fas fa-chevron-right"></i></a>
                                </div>
                            </th>
                            <?php for ($d = 1; $d <= $daysInMon; $d++):
                                $ds  = sprintf('%04d-%02d-%02d', $viewYear, $viewMonth, $d);
                                $dow = date('N', strtotime($ds));
                                $isToday   = $ds === date('Y-m-d');
                                $isSun     = $dow == 7;
                                $isSat     = $dow == 6;
                                $isHoliday = in_array($ds, $holidayDates);
                            ?>
                            <th class="text-center px-0
                                <?= $isToday   ? 'bg-primary'  : '' ?>
                                <?= !$isToday && $isHoliday ? 'bg-danger bg-opacity-75' : '' ?>
                                <?= !$isToday && !$isHoliday && $isSun ? 'text-danger' : '' ?>
                                <?= !$isToday && !$isHoliday && $isSat ? 'text-warning' : '' ?>"
                                style="min-width:34px; font-size:11px; white-space:nowrap;"
                                title="<?= $isHoliday ? 'Ngày lễ' : '' ?>">
                                <div><?= ['','T2','T3','T4','T5','T6','T7','CN'][$dow] ?></div>
                                <div class="fw-bold"><?= $d ?></div>
                                <?php if ($isHoliday): ?><div style="font-size:9px;">🎉</div><?php endif; ?>
                            </th>
                            <?php endfor; ?>
                            <th class="text-center" style="min-width:45px; font-size:11px;">Công</th>
                            <th class="text-center" style="min-width:40px; font-size:11px;">Phép</th>
                            <th class="text-center" style="min-width:40px; font-size:11px;">Vắng</th>
                            <th class="text-center" style="min-width:40px; font-size:11px;">Trễ</th>
                            <th class="text-center" style="min-width:45px; font-size:11px;">OT(h)</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $prevDept = null;
                    foreach ($employees as $emp):
                        if ($emp['dept_name'] !== $prevDept):
                            $prevDept = $emp['dept_name'];
                    ?>
                    <tr class="dept-row">
                        <td colspan="<?= $daysInMon + 6 ?>" class="py-1 ps-3 fw-bold small">
                            🏢 <?= htmlspecialchars($emp['dept_name'] ?? 'Chưa phân phòng ban') ?>
                        </td>
                    </tr>
                    <?php endif;
                        $st = calcStats($emp['id'], $attMap, $leaveMap, $otMap, $viewMonth, $viewYear, $daysInMon, $holidayDates);
                    ?>
                    <tr class="emp-row" data-dept="<?= htmlspecialchars($emp['dept_name'] ?? '') ?>">
                        <!-- Tên nhân viên + ca -->
                        <td class="sticky-col py-1">
                            <div class="d-flex align-items-center gap-1">
                                <div>
                                    <div class="fw-semibold" style="font-size:12px; line-height:1.2;">
                                        <?= htmlspecialchars($emp['full_name']) ?>
                                    </div>
                                    <div style="font-size:10px;" class="text-muted">
                                        <?= $emp['employee_code'] ?>
                                        <?php if ($emp['shift_name']): ?>
                                        &bull; <span style="color:<?= $emp['shift_color'] ?>; font-weight:600;">
                                            <?= htmlspecialchars($emp['shift_name']) ?>
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </td>

                        <!-- Ô từng ngày -->
                        <?php for ($d = 1; $d <= $daysInMon; $d++):
                            $dateStr  = sprintf('%04d-%02d-%02d', $viewYear, $viewMonth, $d);
                            $dow      = date('N', strtotime($dateStr));
                            $isSun    = ($dow == 7);
                            $isFuture = ($dateStr > date('Y-m-d'));
                            $isHoliday = in_array($dateStr, $holidayDates);
                            $att    = $attMap[$emp['id']][$dateStr]  ?? null;
                            $leave  = $leaveMap[$emp['id']][$dateStr] ?? null;
                            $ot     = $otMap[$emp['id']][$dateStr]    ?? null;

                            $bg = ''; $content = ''; $title = '';

                            if ($isSun) {
                                $bg = '#f4f4f4';
                                $content = '<span style="color:#ccc;font-size:10px;">—</span>';
                            } elseif ($isHoliday && !$att) {
                                $bg = '#fff0f0';
                                $content = '<span style="font-size:11px;" title="Ngày lễ">🎉</span>';
                            } elseif ($isFuture) {
                                $bg = '#fafafa';
                            } elseif ($leave && !$att) {
                                $leaveLabels = ['annual'=>'Phép','sick'=>'Ốm','unpaid'=>'KL','other'=>'Khác'];
                                $bg = '#e8f4fd';
                                $content = '<span style="font-size:10px;color:#0dcaf0;font-weight:600;">' . ($leaveLabels[$leave] ?? 'Phép') . '</span>';
                                $title = 'Nghỉ phép';
                            } elseif ($att && $att['check_in']) {
                                $isLate = $att['is_late'];
                                $bg = $isLate ? '#fffbf0' : '#f0fff4';
                                $checkIn  = date('H:i', strtotime($att['check_in']));
                                $checkOut = $att['check_out'] ? date('H:i', strtotime($att['check_out'])) : '?';
                                $title = "Vào: $checkIn | Ra: $checkOut";
                                if ($isLate) $title .= " | Trễ: " . $att['late_minutes'] . "p";
                                if ($ot)     $title .= " | OT: " . $ot['hours'] . "h";
                                $content = '<div style="font-size:10px;line-height:1.3;">';
                                if ($isLate) {
                                    $content .= '<span class="text-warning fw-bold">⚡</span>';
                                } else {
                                    $content .= '<span class="text-success fw-bold">✓</span>';
                                }
                                $content .= '<br><span style="color:#666;">' . $checkIn . '</span>';
                                if ($ot) $content .= '<br><span style="color:#6f42c1;font-size:9px;">OT</span>';
                                $content .= '</div>';
                            } else {
                                $bg = '#fff5f5';
                                $content = '<span style="color:#dc3545;font-size:11px;font-weight:bold;">✗</span>';
                                $title = 'Vắng không phép';
                            }
                        ?>
                        <td class="text-center p-0 att-cell"
                            style="background:<?= $bg ?>; height:42px; vertical-align:middle; cursor:pointer;"
                            title="<?= htmlspecialchars($title) ?>"
                            onclick="showDayDetail(<?= $emp['id'] ?>, '<?= $dateStr ?>', '<?= htmlspecialchars($emp['full_name']) ?>')">
                            <?= $content ?>
                        </td>
                        <?php endfor; ?>

                        <!-- Tổng kết -->
                        <td class="text-center fw-bold text-success small"><?= $st['work_days'] ?></td>
                        <td class="text-center fw-bold text-info small"><?= $st['leave_days'] ?></td>
                        <td class="text-center fw-bold <?= $st['absent_days'] > 0 ? 'text-danger' : 'text-muted' ?> small"><?= $st['absent_days'] ?></td>
                        <td class="text-center small">
                            <?php if ($st['late_count'] > 0): ?>
                            <span class="badge bg-warning text-dark"><?= $st['late_count'] ?></span>
                            <?php else: ?>
                            <span class="text-muted">0</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center small">
                            <?php if ($st['ot_hours'] > 0): ?>
                            <span class="badge bg-purple"><?= number_format($st['ot_hours'],1) ?></span>
                            <?php else: ?>
                            <span class="text-muted">0</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════
         CHẾ ĐỘ XEM: BẢNG TỔNG HỢP
    ══════════════════════════════════════════════ -->
    <?php elseif ($viewMode === 'summary'): ?>

    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white fw-bold d-flex justify-content-between">
            <span>📋 Bảng tổng hợp tháng <?= $viewMonth ?>/<?= $viewYear ?></span>
            <small class="text-muted fw-normal"><?= count($employees) ?> nhân viên</small>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover table-bordered align-middle mb-0" id="summaryTable">
                    <thead class="table-dark">
                        <tr>
                            <th class="sticky-col" style="min-width:180px;">Nhân viên</th>
                            <th class="text-center">Ca</th>
                            <th class="text-center">Ngày công</th>
                            <th class="text-center">Giờ làm</th>
                            <th class="text-center">Nghỉ phép</th>
                            <th class="text-center">Vắng</th>
                            <th class="text-center">Đi trễ</th>
                            <th class="text-center">Tổng phút trễ</th>
                            <th class="text-center">Về sớm</th>
                            <th class="text-center">OT thường</th>
                            <th class="text-center">OT T7/CN</th>
                            <th class="text-center">OT lễ</th>
                            <th class="text-center fw-bold text-warning">Tổng OT</th>
                            <th class="text-center">Làm CN</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $prevDept    = null;
                    $deptTotals  = [];
                    $grandTotals = array_fill_keys(['work_days','total_hours','leave_days','absent_days','late_count','late_minutes','early_count','ot_hours','ot_weekday','ot_weekend','ot_holiday','sunday_work'], 0);

                    foreach ($employees as $emp):
                        if ($emp['dept_name'] !== $prevDept):
                            $prevDept = $emp['dept_name'];
                    ?>
                    <tr class="table-secondary">
                        <td colspan="14" class="fw-bold small py-1 ps-3">
                            🏢 <?= htmlspecialchars($emp['dept_name'] ?? 'Chưa phân phòng ban') ?>
                        </td>
                    </tr>
                    <?php endif;
                        $st = calcStats($emp['id'], $attMap, $leaveMap, $otMap, $viewMonth, $viewYear, $daysInMon, $holidayDates);
                        foreach ($grandTotals as $k => $v) $grandTotals[$k] += $st[$k];
                    ?>
                    <tr>
                        <td class="sticky-col">
                            <div class="fw-semibold small"><?= htmlspecialchars($emp['full_name']) ?></div>
                            <div class="text-muted" style="font-size:10px;">
                                <?= $emp['employee_code'] ?>
                                <?php if ($emp['shift_name']): ?>
                                &bull; <span style="color:<?= $emp['shift_color'] ?>"><?= htmlspecialchars($emp['shift_name']) ?></span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="text-center">
                            <?php if ($emp['shift_name']): ?>
                            <span class="badge" style="background:<?= $emp['shift_color'] ?>; font-size:10px;">
                                <?= htmlspecialchars($emp['shift_name']) ?>
                            </span>
                            <?php else: ?>
                            <span class="text-danger small">Chưa có</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center fw-bold text-success"><?= $st['work_days'] ?></td>
                        <td class="text-center"><?= number_format($st['total_hours'], 1) ?>h</td>
                        <td class="text-center text-info"><?= $st['leave_days'] ?: '—' ?></td>
                        <td class="text-center <?= $st['absent_days'] > 0 ? 'text-danger fw-bold' : 'text-muted' ?>">
                            <?= $st['absent_days'] ?: '—' ?>
                        </td>
                        <td class="text-center">
                            <?php if ($st['late_count'] > 0): ?>
                            <span class="badge bg-warning text-dark"><?= $st['late_count'] ?> lần</span>
                            <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                        </td>
                        <td class="text-center small text-muted">
                            <?= $st['late_minutes'] > 0 ? $st['late_minutes'] . 'p' : '—' ?>
                        </td>
                        <td class="text-center small text-muted">
                            <?= $st['early_count'] > 0 ? $st['early_count'] . ' lần' : '—' ?>
                        </td>
                        <td class="text-center small"><?= $st['ot_weekday'] > 0 ? number_format($st['ot_weekday'],1).'h' : '—' ?></td>
                        <td class="text-center small"><?= $st['ot_weekend'] > 0 ? number_format($st['ot_weekend'],1).'h' : '—' ?></td>
                        <td class="text-center small"><?= $st['ot_holiday'] > 0 ? number_format($st['ot_holiday'],1).'h' : '—' ?></td>
                        <td class="text-center fw-bold">
                            <?php if ($st['ot_hours'] > 0): ?>
                            <span class="badge bg-purple"><?= number_format($st['ot_hours'],1) ?>h</span>
                            <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                        </td>
                        <td class="text-center small text-muted">
                            <?= $st['sunday_work'] > 0 ? $st['sunday_work'] . ' ngày' : '—' ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>

                    <!-- Footer tổng cộng -->
                    <tfoot class="table-dark fw-bold">
                        <tr>
                            <td class="sticky-col" colspan="2">📊 TỔNG CỘNG</td>
                            <td class="text-center text-success"><?= $grandTotals['work_days'] ?></td>
                            <td class="text-center"><?= number_format($grandTotals['total_hours'],1) ?>h</td>
                            <td class="text-center text-info"><?= $grandTotals['leave_days'] ?></td>
                            <td class="text-center text-danger"><?= $grandTotals['absent_days'] ?></td>
                            <td class="text-center text-warning"><?= $grandTotals['late_count'] ?></td>
                            <td class="text-center"><?= $grandTotals['late_minutes'] ?>p</td>
                            <td class="text-center"><?= $grandTotals['early_count'] ?></td>
                            <td class="text-center"><?= number_format($grandTotals['ot_weekday'],1) ?>h</td>
                            <td class="text-center"><?= number_format($grandTotals['ot_weekend'],1) ?>h</td>
                            <td class="text-center"><?= number_format($grandTotals['ot_holiday'],1) ?>h</td>
                            <td class="text-center text-warning"><?= number_format($grandTotals['ot_hours'],1) ?>h</td>
                            <td class="text-center"><?= $grandTotals['sunday_work'] ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    <?php endif; ?>

</div>
</div>

<!-- ══════════════════════════════════════════════
     MODAL: Chi tiết chấm công 1 ngày
══════════════════════════════════════════════ -->
<div class="modal fade" id="dayDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h6 class="modal-title fw-bold" id="dayDetailTitle">Chi tiết chấm công</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="dayDetailBody">
                <div class="text-center py-3"><i class="fas fa-spinner fa-spin"></i> Đang tải...</div>
            </div>
        </div>
    </div>
</div>

<style>
/* ── Layout ── */
.sticky-col {
    position: sticky; left: 0;
    background: #fff; z-index: 3;
    box-shadow: 2px 0 5px rgba(0,0,0,.08);
}
.att-table thead th.sticky-col { background: #212529; z-index: 4; }
.dept-row td { background: #e9ecef !important; }

/* ── Cell ── */
.att-cell { transition: filter .15s; }
.att-cell:hover { filter: brightness(.88); }

/* ── Badge màu tím (OT) ── */
.bg-purple { background-color: #6f42c1 !important; color: #fff; }

/* ── Thanh nút điều hướng ── */
.btn-xs { padding: 1px 6px; font-size: 11px; }

/* ── Print ── */
@media print {
    .main-content { margin-left: 0 !important; }
    .sidebar, nav.navbar, .card-header form,
    .btn, .modal { display: none !important; }
    .att-table { font-size: 9px; }
    .sticky-col { position: static; box-shadow: none; }
}
</style>

<script>
// ── Modal chi tiết 1 ô chấm công ──────────────────────────────────────────
async function showDayDetail(userId, dateStr, empName) {
    document.getElementById('dayDetailTitle').textContent = `📅 ${empName} — ${dateStr}`;
    document.getElementById('dayDetailBody').innerHTML = '<div class="text-center py-3"><i class="fas fa-spinner fa-spin"></i> Đang tải...</div>';
    new bootstrap.Modal(document.getElementById('dayDetailModal')).show();

    try {
        const res  = await fetch(`/erp/api/attendance/detail.php?user_id=${userId}&date=${dateStr}`);
        const data = await res.json();

        let html = `<div class="row g-3">`;

        // Thông tin chấm công
        html += `<div class="col-md-6">
            <div class="card border-0 bg-light">
                <div class="card-body">
                    <h6 class="fw-bold mb-3">⏰ Chấm công</h6>
                    <table class="table table-sm mb-0">
                        <tr><th>Giờ vào</th><td class="text-success fw-bold">${data.att?.check_in ? data.att.check_in.substring(11,16) : '—'}</td></tr>
                        <tr><th>Giờ ra</th><td class="text-danger fw-bold">${data.att?.check_out ? data.att.check_out.substring(11,16) : '⚠️ Chưa ra'}</td></tr>
                        <tr><th>Số giờ</th><td>${data.att?.work_hours ?? '—'} giờ</td></tr>
                        <tr><th>Đi trễ</th><td>${data.att?.is_late ? `<span class="badge bg-warning text-dark">⚡ ${data.att.late_minutes} phút</span>` : '<span class="text-success">Đúng giờ</span>'}</td></tr>
                        <tr><th>Nguồn</th><td><span class="badge bg-secondary">${data.att?.source === 'machine' ? '🖥️ Máy chấm' : '✍️ Thủ công'}</span></td></tr>
                    </table>
                </div>
            </div>
        </div>`;

        // OT & nghỉ phép
        html += `<div class="col-md-6">
            <div class="card border-0 bg-light">
                <div class="card-body">
                    <h6 class="fw-bold mb-3">📋 OT & Nghỉ phép</h6>`;
        if (data.ot) {
            const otTypes = {weekday:'Ngày thường',weekend:'Cuối tuần',holiday:'Ngày lễ'};
            html += `<div class="alert alert-purple py-2 mb-2">
                        <strong>🌙 OT ${data.ot.hours}h</strong><br>
                        <small>${data.ot.start_time}–${data.ot.end_time} (${otTypes[data.ot.ot_type]||data.ot.ot_type})</small>
                     </div>`;
        }
        if (data.leave) {
            const leaveTypes = {annual:'Phép năm',sick:'Nghỉ ốm',unpaid:'Không lương',other:'Khác'};
            html += `<div class="alert alert-info py-2 mb-2">
                        <strong>🏖️ Nghỉ phép</strong><br>
                        <small>${leaveTypes[data.leave.leave_type]||data.leave.leave_type}: ${data.leave.reason}</small>
                     </div>`;
        }
        if (!data.ot && !data.leave) html += `<p class="text-muted small">Không có OT hoặc đơn nghỉ</p>`;
        html += `</div></div></div>`;

        // Ca làm việc
        if (data.shift) {
            html += `<div class="col-12">
                <div class="card border-0" style="border-left:4px solid ${data.shift.color}!important;">
                    <div class="card-body py-2">
                        <span class="badge me-2" style="background:${data.shift.color}">${data.shift.shift_name}</span>
                        <small class="text-muted">Giờ chuẩn: ${data.shift.start_time.substring(0,5)} – ${data.shift.end_time.substring(0,5)} | ${data.shift.work_hours}h/ca</small>
                    </div>
                </div>
            </div>`;
        }

        html += `</div>`;
        document.getElementById('dayDetailBody').innerHTML = html;
    } catch(e) {
        document.getElementById('dayDetailBody').innerHTML = '<div class="alert alert-danger">Lỗi tải dữ liệu.</div>';
    }
}

// ── Export Excel (dùng SheetJS) ───────────────────────────────────────────
function exportExcel() {
    const tableId = document.getElementById('summaryTable') ? 'summaryTable' : 'attTable';
    const table   = document.getElementById(tableId);
    if (!table) { alert('Vui lòng chuyển sang chế độ Tổng hợp để xuất Excel.'); return; }

    const wb  = XLSX.utils.book_new();
    const ws  = XLSX.utils.table_to_sheet(table);
    XLSX.utils.book_append_sheet(wb, ws, 'Chấm công T<?= $viewMonth ?>/<?= $viewYear ?>');
    XLSX.writeFile(wb, `ChamCong_T<?= $viewMonth ?>_<?= $viewYear ?>.xlsx`);
}
</script>

<!-- SheetJS cho xuất Excel -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

<?php include $_SERVER['DOCUMENT_ROOT'] . '/erp/includes/footer.php'; ?>