<?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';

// ── Autoload PhpSpreadsheet ──
$autoloadPaths = [
    $_SERVER['DOCUMENT_ROOT'] . '/erp/vendor/autoload.php',
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../../../vendor/autoload.php',
];
$spreadsheetLoaded = false;
foreach ($autoloadPaths as $path) {
    if (file_exists($path)) { require_once $path; $spreadsheetLoaded = true; break; }
}

requireRole('production', 'manager', 'director', 'accountant');

$pdo        = getDBConnection();
$user       = currentUser();
$isDirector = hasRole('director');

// ══════════════════════════════════════════════════════════
// IMPORT OT TỪ EXCEL
// ══════════════════════════════════════════════════════════
$importResult = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && ($_POST['action'] ?? '') === 'import_ot_excel'
    && !empty($_FILES['ot_import_file']['tmp_name'])) {

    if (!$spreadsheetLoaded) {
        $importResult = ['error' => 'Thư viện PhpSpreadsheet chưa được cài. Chạy: composer require phpoffice/phpspreadsheet'];
    } else {
        $tmpFile  = $_FILES['ot_import_file']['tmp_name'];
        $origName = $_FILES['ot_import_file']['name'];
        $ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

        try {
            $reader = match($ext) {
                'xlsx' => new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(),
                'xls'  => new \PhpOffice\PhpSpreadsheet\Reader\Xls(),
                'ods'  => new \PhpOffice\PhpSpreadsheet\Reader\Ods(),
                default => null,
            };

            if (!$reader) {
                $importResult = ['error' => 'Chỉ hỗ trợ .xlsx, .xls, .ods'];
            } else {
                $reader->setReadDataOnly(true);
                $spreadsheet = $reader->load($tmpFile);
                $sheet       = $spreadsheet->getActiveSheet();
                $rows        = $sheet->toArray(null, true, true, false);

                // ── Map employee_code → user_id ──
                $empMap = [];
                foreach ($pdo->query("SELECT id, employee_code FROM users WHERE is_active=1")->fetchAll() as $e) {
                    $empMap[$e['employee_code']] = $e['id'];
                }

                // ── Lấy ca mặc định ──
                $defaultShift = $pdo->query("SELECT id FROM work_shifts LIMIT 1")->fetch();
                $defaultShiftId = $defaultShift ? $defaultShift['id'] : null;

                $inserted = 0; $skipped = 0; $errors = [];

                foreach ($rows as $rowIdx => $row) {
                    if ($rowIdx === 0) continue; // bỏ header

                    $rawDate  = trim((string)($row[0] ?? ''));
                    $maNV     = trim((string)($row[1] ?? ''));
                    $rawHours = trim((string)($row[3] ?? ''));

                    // Bỏ dòng trống
                    if (empty($rawDate) && empty($maNV)) { $skipped++; continue; }
                    if (empty($maNV) || empty($rawDate))  { $skipped++; continue; }

                    // ── Parse ngày ──
                    $otDate = null;
                    if (is_numeric($rawDate) && (float)$rawDate > 1000) {
                        $otDate = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject((float)$rawDate)->format('Y-m-d');
                    } elseif (preg_match('#^(\d{1,2})/(\d{1,2})/(\d{4})$#', $rawDate, $m)) {
                        $otDate = sprintf('%04d-%02d-%02d', $m[3], $m[2], $m[1]);
                    } elseif (preg_match('#^(\d{4})-(\d{2})-(\d{2})$#', $rawDate)) {
                        $otDate = $rawDate;
                    } elseif (preg_match('#^(\d{1,2})-(\d{1,2})-(\d{4})$#', $rawDate, $m)) {
                        $otDate = sprintf('%04d-%02d-%02d', $m[3], $m[2], $m[1]);
                    } else {
                        $ts = strtotime($rawDate);
                        if ($ts) $otDate = date('Y-m-d', $ts);
                    }

                    if (!$otDate || !strtotime($otDate)) {
                        $errors[] = "Dòng " . ($rowIdx + 1) . ": ngày '$rawDate' không đọc được";
                        $skipped++; continue;
                    }

                    // ── Tìm user ──
                    if (!isset($empMap[$maNV])) {
                        $errors[] = "Dòng " . ($rowIdx + 1) . ": mã NV '$maNV' không tìm thấy";
                        $skipped++; continue;
                    }
                    $userId = $empMap[$maNV];

                    // ── Parse số giờ OT ──
                    $hours = (float)str_replace(',', '.', $rawHours);
                    if ($hours <= 0 || $hours > 24) {
                        $errors[] = "Dòng " . ($rowIdx + 1) . ": số giờ OT '$rawHours' không hợp lệ";
                        $skipped++; continue;
                    }

                    // ── Xác định loại OT theo ngày ──
                    $dow     = date('N', strtotime($otDate)); // 1=T2...7=CN
                    $isHol   = $pdo->prepare("SELECT id FROM holidays WHERE holiday_date=?");
                    $isHol->execute([$otDate]);
                    $otType  = $isHol->fetch() ? 'holiday' : ($dow == 7 || $dow == 6 ? 'weekend' : 'weekday');

                    // ── Tạo giờ OT mặc định (bắt đầu 17:00) ──
                    $startTime = '17:00:00';
                    $endH      = 17 + (int)$hours;
                    $endM      = round(($hours - floor($hours)) * 60);
                    $endTime   = sprintf('%02d:%02d:00', $endH % 24, $endM);

                    // ── Kiểm tra đã tồn tại chưa (cùng user + ngày) ──
                    $existStmt = $pdo->prepare("SELECT id FROM overtime_requests WHERE user_id=? AND ot_date=?");
                    $existStmt->execute([$userId, $otDate]);

                    if ($existStmt->fetch()) {
                        // Cập nhật nếu đã có
                        $pdo->prepare("
                            UPDATE overtime_requests
                            SET hours=?, ot_type=?, start_time=?, end_time=?,
                                status='pending', approved_by=NULL, approved_at=NULL
                            WHERE user_id=? AND ot_date=?
                        ")->execute([$hours, $otType, $startTime, $endTime, $userId, $otDate]);
                    } else {
                        // Thêm mới
                        $pdo->prepare("
                            INSERT INTO overtime_requests
                                (user_id, ot_date, hours, ot_type, start_time, end_time,
                                 shift_id, reason, status, created_by)
                            VALUES (?,?,?,?,?,?,?,?,?,?)
                        ")->execute([
                            $userId, $otDate, $hours, $otType,
                            $startTime, $endTime, $defaultShiftId,
                            'Import từ Excel bởi ' . $user['full_name'],
                            'pending', $user['id']
                        ]);
                    }
                    $inserted++;
                }

                $importResult = [
                    'inserted' => $inserted,
                    'skipped'  => $skipped,
                    'errors'   => $errors,
                ];
            }
        } catch (\Exception $e) {
            $importResult = ['error' => 'Lỗi đọc file: ' . $e->getMessage()];
        }
    }
}

// ══════════════════════════════════════════════════════════
// XỬ LÝ CÁC ACTION KHÁC
// ══════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')
    && ($_POST['action'] ?? '') !== 'import_ot_excel') {

    $action        = $_POST['action'] ?? '';
    $ot_id         = (int)($_POST['ot_id'] ?? 0);
    $reject_reason = trim($_POST['reject_reason'] ?? '');

    // Duyệt 1 đơn
    if ($action === 'approve') {
        $stmt = $pdo->prepare("UPDATE overtime_requests SET status='approved', approved_by=?, approved_at=NOW() WHERE id=? AND status='pending'");
        $stmt->execute([$user['id'], $ot_id]);
        if ($stmt->rowCount()) {
            $ot = $pdo->prepare("SELECT user_id, ot_date, start_time, end_time, hours FROM overtime_requests WHERE id=?");
            $ot->execute([$ot_id]);
            $otData = $ot->fetch();
            $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, reference_id) VALUES (?,?,?,'ot_approved',?)")
                ->execute([$otData['user_id'], '✅ Đơn OT được duyệt',
                    'Đơn OT ngày '.formatDate($otData['ot_date']).' ('.$otData['start_time'].'–'.$otData['end_time'].', '.$otData['hours'].' giờ) đã được duyệt bởi '.$user['full_name'],
                    $ot_id]);
            setFlash('success', '✅ Đã duyệt đơn OT.');
        }
        header('Location: /erp/modules/attendance/ot_manage.php?'.http_build_query($_GET)); exit();
    }

    // Từ chối 1 đơn
    if ($action === 'reject') {
        if (empty($reject_reason)) {
            setFlash('danger', '❌ Vui lòng nhập lý do từ chối.');
        } else {
            $stmt = $pdo->prepare("UPDATE overtime_requests SET status='rejected', approved_by=?, approved_at=NOW(), reject_reason=? WHERE id=? AND status='pending'");
            $stmt->execute([$user['id'], $reject_reason, $ot_id]);
            if ($stmt->rowCount()) {
                $ot = $pdo->prepare("SELECT user_id, ot_date FROM overtime_requests WHERE id=?");
                $ot->execute([$ot_id]);
                $otData = $ot->fetch();
                $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, reference_id) VALUES (?,?,?,'ot_rejected',?)")
                    ->execute([$otData['user_id'], '❌ Đơn OT bị từ chối',
                        'Đơn OT ngày '.formatDate($otData['ot_date']).' bị từ chối. Lý do: '.$reject_reason,
                        $ot_id]);
                setFlash('warning', '⚠️ Đã từ chối đơn OT.');
            }
        }
        header('Location: /erp/modules/attendance/ot_manage.php?'.http_build_query($_GET)); exit();
    }

    // Duyệt hàng loạt
    if ($action === 'bulk_approve') {
        $ids = $_POST['selected_ids'] ?? [];
        if (empty($ids)) {
            setFlash('danger', 'Vui lòng chọn ít nhất 1 đơn.');
        } else {
            $count = 0;
            foreach ($ids as $id) {
                $id   = (int)$id;
                $stmt = $pdo->prepare("UPDATE overtime_requests SET status='approved', approved_by=?, approved_at=NOW() WHERE id=? AND status='pending'");
                $stmt->execute([$user['id'], $id]);
                if ($stmt->rowCount()) {
                    $count++;
                    $ot = $pdo->prepare("SELECT user_id, ot_date, hours FROM overtime_requests WHERE id=?");
                    $ot->execute([$id]);
                    $otData = $ot->fetch();
                    $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, reference_id) VALUES (?,?,?,'ot_approved',?)")
                        ->execute([$otData['user_id'], '✅ Đơn OT được duyệt',
                            'Đơn OT ngày '.formatDate($otData['ot_date']).' ('.$otData['hours'].' giờ) đã được duyệt.', $id]);
                }
            }
            setFlash('success', "✅ Đã duyệt <strong>$count</strong> đơn OT.");
        }
        header('Location: /erp/modules/attendance/ot_manage.php?'.http_build_query($_GET)); exit();
    }

    // Xoá 1 đơn OT
    if ($action === 'delete_ot' && $isDirector && $ot_id) {
        $stmt = $pdo->prepare("DELETE FROM overtime_requests WHERE id=?");
        $stmt->execute([$ot_id]);
        setFlash($stmt->rowCount() ? 'success' : 'warning',
                 $stmt->rowCount() ? '🗑️ Đã xoá đơn OT.' : 'Không tìm thấy đơn.');
        header('Location: /erp/modules/attendance/ot_manage.php?'.http_build_query($_GET)); exit();
    }

    // Xoá hàng loạt OT
    if ($action === 'bulk_delete_ot' && $isDirector) {
        $ids = array_map('intval', $_POST['selected_ids'] ?? []);
        if (empty($ids)) {
            setFlash('danger', 'Vui lòng chọn ít nhất 1 đơn.');
        } else {
            $in   = implode(',', $ids);
            $stmt = $pdo->query("DELETE FROM overtime_requests WHERE id IN ($in)");
            setFlash('success', "🗑️ Đã xoá <strong>{$stmt->rowCount()}</strong> đơn OT.");
        }
        header('Location: /erp/modules/attendance/ot_manage.php?'.http_build_query($_GET)); exit();
    }
}

// ── BỘ LỌC ──
$filterStatus = $_GET['status']    ?? 'pending';
$filterDept   = (int)($_GET['dept']    ?? 0);
$filterMonth  = (int)($_GET['month']   ?? date('m'));
$filterYear   = (int)($_GET['year']    ?? date('Y'));
$filterUser   = (int)($_GET['user_id'] ?? 0);

$sql    = "
    SELECT ot.*, u.full_name, u.employee_code, d.name AS dept_name,
           ws.shift_name, ws.color AS shift_color,
           ws.ot_multiplier, ws.weekend_multiplier, ws.holiday_multiplier,
           a.full_name AS approver_name
    FROM overtime_requests ot
    JOIN users u ON ot.user_id = u.id
    LEFT JOIN departments d ON u.department_id = d.id
    LEFT JOIN work_shifts ws ON ot.shift_id = ws.id
    LEFT JOIN users a ON ot.approved_by = a.id
    WHERE MONTH(ot.ot_date) = ? AND YEAR(ot.ot_date) = ?
";
$params = [$filterMonth, $filterYear];
if ($filterStatus !== 'all') { $sql .= " AND ot.status = ?";       $params[] = $filterStatus; }
if ($filterDept)             { $sql .= " AND u.department_id = ?"; $params[] = $filterDept; }
if ($filterUser)             { $sql .= " AND ot.user_id = ?";      $params[] = $filterUser; }
$sql .= " ORDER BY FIELD(ot.status,'pending','approved','rejected'), ot.ot_date DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$requests = $stmt->fetchAll();

$statsQ = $pdo->prepare("
    SELECT COUNT(*) AS total,
        SUM(status='pending')  AS pending,
        SUM(status='approved') AS approved,
        SUM(status='rejected') AS rejected,
        COALESCE(SUM(CASE WHEN status='approved' THEN hours ELSE 0 END),0) AS total_hours,
        COALESCE(SUM(CASE WHEN status='approved' AND ot_type='weekday' THEN hours ELSE 0 END),0) AS weekday_hours,
        COALESCE(SUM(CASE WHEN status='approved' AND ot_type='weekend' THEN hours ELSE 0 END),0) AS weekend_hours,
        COALESCE(SUM(CASE WHEN status='approved' AND ot_type='holiday' THEN hours ELSE 0 END),0) AS holiday_hours
    FROM overtime_requests WHERE MONTH(ot_date)=? AND YEAR(ot_date)=?
");
$statsQ->execute([$filterMonth, $filterYear]);
$stats = $statsQ->fetch();
foreach (['total_hours','weekday_hours','weekend_hours','holiday_hours','pending','approved','rejected','total'] as $k) {
    $stats[$k] = $stats[$k] ?? 0;
}

$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();

$otTypeLabel = ['weekday'=>['Ngày thường','secondary'],'weekend'=>['Cuối tuần','warning'],'holiday'=>['Ngày lễ','danger']];
$statusLabel = ['pending'=>['⌛ Chờ duyệt','warning'],'approved'=>['✅ Đã duyệt','success'],'rejected'=>['❌ Từ chối','danger']];

$csrf = generateCSRF();
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">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="mb-1">✅ Duyệt Tăng ca (OT)</h4>
            <p class="text-muted small mb-0">Tháng <?= $filterMonth ?>/<?= $filterYear ?></p>
        </div>
        <div class="d-flex gap-2 flex-wrap justify-content-end">
            <!-- Nút Import Excel OT -->
            <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#importOTModal">
                <i class="fas fa-file-excel me-1"></i>Import OT từ Excel
            </button>
            <?php if ($isDirector && !empty($requests)): ?>
            <button class="btn btn-danger btn-sm" id="btnBulkDeleteOT" disabled
                    onclick="confirmBulkDeleteOT()">
                <i class="fas fa-trash-alt me-1"></i>Xoá đã chọn
                <span id="otDeleteCount" class="badge bg-white text-danger ms-1">0</span>
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?php showFlash(); ?>

    <!-- ── Kết quả Import ── -->
    <?php if ($importResult): ?>
    <div class="alert <?= isset($importResult['error']) ? 'alert-danger' : 'alert-success' ?> alert-dismissible fade show">
        <?php if (isset($importResult['error'])): ?>
            <i class="fas fa-times-circle me-2"></i><strong>Lỗi:</strong> <?= htmlspecialchars($importResult['error']) ?>
        <?php else: ?>
            <i class="fas fa-check-circle me-2"></i>
            <strong>Import OT hoàn tất!</strong> &nbsp;
            <span class="badge bg-success">✅ Đã tạo/cập nhật: <?= $importResult['inserted'] ?></span> &nbsp;
            <span class="badge bg-secondary">⏭️ Bỏ qua: <?= $importResult['skipped'] ?></span>
            <?php if (!empty($importResult['errors'])): ?>
            <hr class="my-2">
            <div class="small">
                <strong>⚠️ <?= count($importResult['errors']) ?> cảnh báo:</strong><br>
                <?php foreach (array_slice($importResult['errors'], 0, 8) as $err): ?>
                    — <?= htmlspecialchars($err) ?><br>
                <?php endforeach; ?>
                <?php if (count($importResult['errors']) > 8): ?>
                    <em>...và <?= count($importResult['errors']) - 8 ?> cảnh báo khác</em>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Thống kê -->
    <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-warning"><?= $stats['pending'] ?></div>
                <div class="small text-muted">⌛ Chờ duyệt</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"><?= $stats['approved'] ?></div>
                <div class="small text-muted">✅ Đã duyệt</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-primary"><?= number_format($stats['total_hours'],1) ?></div>
                <div class="small text-muted">⏱️ Tổng giờ OT</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="d-flex justify-content-center gap-2">
                    <div><div class="fw-bold text-secondary"><?= number_format($stats['weekday_hours'],1) ?>h</div><div style="font-size:10px" class="text-muted">Thường</div></div>
                    <div><div class="fw-bold text-warning"><?= number_format($stats['weekend_hours'],1) ?>h</div><div style="font-size:10px" class="text-muted">T7/CN</div></div>
                    <div><div class="fw-bold text-danger"><?= number_format($stats['holiday_hours'],1) ?>h</div><div style="font-size:10px" class="text-muted">Lễ</div></div>
                </div>
                <div class="small text-muted mt-1">📊 Phân loại giờ</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">
                <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==$filterMonth?'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==$filterYear?'selected':'' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label small fw-semibold mb-1">Trạng thái</label>
                    <select name="status" class="form-select form-select-sm">
                        <option value="pending"  <?= $filterStatus==='pending'  ?'selected':'' ?>>⌛ Chờ duyệt</option>
                        <option value="approved" <?= $filterStatus==='approved' ?'selected':'' ?>>✅ Đã duyệt</option>
                        <option value="rejected" <?= $filterStatus==='rejected' ?'selected':'' ?>>❌ Từ chối</option>
                        <option value="all"      <?= $filterStatus==='all'      ?'selected':'' ?>>Tất cả</option>
                    </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-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ả nhân viên</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">Lọc</button>
                    <a href="/erp/modules/attendance/ot_manage.php" class="btn btn-outline-secondary btn-sm">↺</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Danh sách đơn OT -->
    <form method="POST" id="otForm">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="action"     id="otFormAction" value="bulk_approve">

        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <span class="fw-bold">
                    📋 Danh sách đơn OT
                    <span class="badge bg-secondary ms-1"><?= count($requests) ?></span>
                </span>
                <?php if (!empty($requests)): ?>
                <div class="d-flex gap-2 align-items-center flex-wrap">
                    <div class="form-check mb-0">
                        <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleOTAll(this)">
                        <label class="form-check-label small" for="selectAll">Chọn tất cả</label>
                    </div>
                    <?php if ($filterStatus === 'pending'): ?>
                    <button type="button" class="btn btn-success btn-sm" id="bulkApproveBtn" disabled onclick="submitBulkApprove()">
                        <i class="fas fa-check-double me-1"></i>Duyệt hàng loạt
                        <span id="bulkCount" class="badge bg-white text-success ms-1">0</span>
                    </button>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <div class="card-body p-0">
                <?php if (empty($requests)): ?>
                <div class="text-center text-muted py-5">
                    <i class="fas fa-clipboard-check fa-3x mb-3 d-block opacity-25"></i>
                    Không có đơn OT nào
                </div>
                <?php else: ?>

                <!-- Desktop -->
                <div class="table-responsive d-none d-md-block">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="40">
                                    <input type="checkbox" class="form-check-input" id="selectAllTh" onchange="toggleOTAll(this)">
                                </th>
                                <th>Nhân viên</th>
                                <th>Ngày OT</th>
                                <th>Giờ OT</th>
                                <th>Loại</th>
                                <th>Hệ số</th>
                                <th>Lý do</th>
                                <th>Ngày gửi</th>
                                <th>Trạng thái</th>
                                <th class="text-center">Thao tác</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($requests as $ot):
                            $otp  = $otTypeLabel[$ot['ot_type']] ?? ['?','secondary'];
                            $st   = $statusLabel[$ot['status']];
                            $mult = match($ot['ot_type']) {
                                'weekend' => $ot['weekend_multiplier'] ?? 2.0,
                                'holiday' => $ot['holiday_multiplier'] ?? 3.0,
                                default   => $ot['ot_multiplier'] ?? 1.5
                            };
                        ?>
                        <tr class="<?= $ot['status']==='rejected'?'opacity-50':'' ?>">
                            <td>
                                <input type="checkbox" name="selected_ids[]" value="<?= $ot['id'] ?>"
                                       class="form-check-input ot-check" onchange="updateOTBtn()">
                            </td>
                            <td>
                                <div class="fw-semibold small"><?= htmlspecialchars($ot['full_name']) ?></div>
                                <div class="text-muted" style="font-size:11px;"><?= $ot['employee_code'] ?> · <?= htmlspecialchars($ot['dept_name']??'') ?></div>
                            </td>
                            <td>
                                <div class="fw-semibold small"><?= formatDate($ot['ot_date']) ?></div>
                                <div style="font-size:11px;" class="text-muted"><?= date('l', strtotime($ot['ot_date'])) ?></div>
                            </td>
                            <td>
                                <div class="fw-bold text-primary"><?= $ot['hours'] ?>h</div>
                                <div style="font-size:11px;" class="text-muted"><?= substr($ot['start_time'],0,5) ?>–<?= substr($ot['end_time'],0,5) ?></div>
                            </td>
                            <td><span class="badge bg-<?= $otp[1] ?> text-<?= $otp[1]==='warning'?'dark':'white' ?>"><?= $otp[0] ?></span></td>
                            <td>
                                <?php if ($ot['shift_name']): ?>
                                <span class="badge" style="background:<?= $ot['shift_color'] ?>;font-size:11px;"><?= $mult ?>x</span>
                                <?php else: ?><span class="text-muted small">—</span><?php endif; ?>
                            </td>
                            <td><small class="text-muted" title="<?= htmlspecialchars($ot['reason']) ?>"><?= mb_strimwidth(htmlspecialchars($ot['reason']),0,30,'...') ?></small></td>
                            <td><small class="text-muted"><?= formatDate($ot['created_at'],'d/m H:i') ?></small></td>
                            <td>
                                <span class="badge bg-<?= $st[1] ?> text-<?= $st[1]==='warning'?'dark':'white' ?>"><?= $st[0] ?></span>
                                <?php if ($ot['status']!=='pending' && $ot['approver_name']): ?>
                                <div style="font-size:10px;" class="text-muted"><?= htmlspecialchars($ot['approver_name']) ?></div>
                                <?php endif; ?>
                                <?php if ($ot['status']==='rejected' && $ot['reject_reason']): ?>
                                <div style="font-size:10px;" class="text-danger"><?= mb_strimwidth(htmlspecialchars($ot['reject_reason']),0,20,'...') ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <div class="d-flex gap-1 justify-content-center">
                                    <?php if ($ot['status'] === 'pending'): ?>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                                        <input type="hidden" name="action"     value="approve">
                                        <input type="hidden" name="ot_id"      value="<?= $ot['id'] ?>">
                                        <button class="btn btn-xs btn-success"
                                                onclick="return confirm('Duyệt đơn OT của <?= htmlspecialchars(addslashes($ot['full_name'])) ?>?')"
                                                title="Duyệt"><i class="fas fa-check"></i></button>
                                    </form>
                                    <button class="btn btn-xs btn-warning"
                                            onclick="showRejectModal(<?= $ot['id'] ?>, '<?= htmlspecialchars(addslashes($ot['full_name'])) ?>')"
                                            title="Từ chối"><i class="fas fa-times"></i></button>
                                    <?php else: ?>
                                    <button class="btn btn-xs btn-outline-secondary"
                                            onclick="showDetail(<?= htmlspecialchars(json_encode($ot)) ?>)"
                                            title="Chi tiết"><i class="fas fa-eye"></i></button>
                                    <?php endif; ?>
                                    <?php if ($isDirector): ?>
                                    <button type="button" class="btn btn-xs btn-outline-danger"
                                            title="Xoá"
                                            onclick="confirmDeleteOT(<?= $ot['id'] ?>, '<?= htmlspecialchars(addslashes($ot['full_name'])) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Mobile -->
                <div class="d-md-none">
                    <?php foreach ($requests as $ot):
                        $otp = $otTypeLabel[$ot['ot_type']] ?? ['?','secondary'];
                        $st  = $statusLabel[$ot['status']];
                    ?>
                    <div class="p-3 border-bottom">
                        <div class="d-flex justify-content-between mb-1">
                            <div>
                                <strong class="small"><?= htmlspecialchars($ot['full_name']) ?></strong>
                                <span class="text-muted small ms-1">(<?= $ot['employee_code'] ?>)</span>
                            </div>
                            <span class="badge bg-<?= $st[1] ?> text-<?= $st[1]==='warning'?'dark':'white' ?>"><?= $st[0] ?></span>
                        </div>
                        <div class="d-flex flex-wrap gap-2 small mb-2">
                            <span><i class="fas fa-calendar me-1 text-primary"></i><?= formatDate($ot['ot_date']) ?></span>
                            <span><i class="fas fa-clock me-1 text-success"></i><?= $ot['hours'] ?>h</span>
                            <span class="badge bg-<?= $otp[1] ?>"><?= $otp[0] ?></span>
                        </div>
                        <div class="small text-muted mb-2"><?= htmlspecialchars($ot['reason']) ?></div>
                        <div class="d-flex gap-2">
                            <?php if ($ot['status'] === 'pending'): ?>
                            <form method="POST" class="d-inline flex-grow-1">
                                <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                                <input type="hidden" name="action" value="approve">
                                <input type="hidden" name="ot_id"  value="<?= $ot['id'] ?>">
                                <button class="btn btn-success btn-sm w-100">✅ Duyệt</button>
                            </form>
                            <button class="btn btn-warning btn-sm flex-grow-1"
                                    onclick="showRejectModal(<?= $ot['id'] ?>, '<?= htmlspecialchars(addslashes($ot['full_name'])) ?>')">
                                ❌ Từ chối
                            </button>
                            <?php endif; ?>
                            <?php if ($isDirector): ?>
                            <button type="button" class="btn btn-outline-danger btn-sm"
                                    onclick="confirmDeleteOT(<?= $ot['id'] ?>, '<?= htmlspecialchars(addslashes($ot['full_name'])) ?>')">
                                <i class="fas fa-trash"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </form>
</div>
</div>

<!-- ══ MODAL Import OT Excel ══ -->
<div class="modal fade" id="importOTModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="import_ot_excel">
                <div class="modal-header" style="background:linear-gradient(135deg,#f59e0b,#d97706);color:#fff;">
                    <h5 class="modal-title fw-bold">
                        <i class="fas fa-file-excel me-2"></i>Import Đăng ký OT từ Excel
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">

                    <!-- Cấu trúc file -->
                    <div class="card border-warning mb-3">
                        <div class="card-header bg-warning bg-opacity-10 py-2 text-warning fw-bold small">
                            <i class="fas fa-info-circle me-1"></i>Cấu trúc file Excel yêu cầu
                        </div>
                        <div class="card-body py-2 px-3">
                            <div class="table-responsive">
                                <table class="table table-sm table-bordered mb-0" style="font-size:12px;">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>A — ngày</th>
                                            <th>B — mã nhân viên</th>
                                            <th>C — tên</th>
                                            <th>D — số giờ OT</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>02/04/2026</td>
                                            <td>DNA24030001</td>
                                            <td>Dương Đức Minh</td>
                                            <td class="text-warning fw-bold">3</td>
                                        </tr>
                                        <tr>
                                            <td>05/04/2026</td>
                                            <td>DNA24030002</td>
                                            <td>Nguyễn Đình Thắng</td>
                                            <td class="text-warning fw-bold">2.5</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <ul class="small text-muted mb-0 mt-2">
                                <li>Dòng đầu là <strong>tiêu đề</strong> (ngày, mã nhân viên, tên, số giờ OT)</li>
                                <li>Cột <strong>ngày</strong>: định dạng <code>dd/mm/yyyy</code></li>
                                <li>Cột <strong>mã nhân viên</strong>: phải khớp mã trong hệ thống</li>
                                <li>Cột <strong>số giờ OT</strong>: số thực (VD: 2, 3.5, 4)</li>
                                <li>Loại OT tự động xác định: <span class="badge bg-danger">Ngày lễ</span> <span class="badge bg-warning text-dark">Cuối tuần</span> <span class="badge bg-secondary">Ngày thường</span></li>
                                <li>Giờ bắt đầu OT mặc định: <strong>17:00</strong></li>
                                <li>Nếu đã tồn tại (cùng NV + ngày) → <strong>cập nhật đè</strong>, trạng thái reset về <em>Chờ duyệt</em></li>
                            </ul>
                        </div>
                    </div>

                    <!-- Nút tải template -->
                    <div class="mb-3">
                        <button type="button" class="btn btn-outline-success btn-sm" onclick="downloadOTTemplate()">
                            <i class="fas fa-download me-1"></i>Tải file mẫu (.xlsx)
                        </button>
                    </div>

                    <!-- Upload -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-upload me-1 text-warning"></i>
                            Chọn file Excel <span class="text-danger">*</span>
                        </label>
                        <input type="file" name="ot_import_file" id="otImportFileInput"
                               class="form-control" accept=".xlsx,.xls,.ods" required
                               onchange="previewOTFile(this)">
                        <div class="form-text">Hỗ trợ: <strong>.xlsx</strong>, .xls, .ods</div>
                    </div>

                    <div id="otFilePreviewBox" class="d-none">
                        <div class="alert alert-light border d-flex align-items-center gap-3 py-2">
                            <i class="fas fa-file-excel fa-2x text-warning"></i>
                            <div id="otFilePreviewText" class="small"></div>
                        </div>
                    </div>

                    <?php if (!$spreadsheetLoaded): ?>
                    <div class="alert alert-danger py-2 small mb-0">
                        <i class="fas fa-exclamation-circle me-1"></i>
                        <strong>⚠️ Thư viện PhpSpreadsheet chưa được cài!</strong>
                        Chạy: <code>composer require phpoffice/phpspreadsheet</code>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer border-0 pt-0">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>Huỷ
                    </button>
                    <button type="submit" class="btn btn-warning fw-bold" <?= !$spreadsheetLoaded ? 'disabled' : '' ?>>
                        <i class="fas fa-file-import me-1"></i>Import OT ngay
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Modal Từ chối OT ── -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="rejectForm">
                <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                <input type="hidden" name="action"     value="reject">
                <input type="hidden" name="ot_id"      id="rejectOtId">
                <div class="modal-header border-0">
                    <h6 class="modal-title">❌ Từ chối đơn OT của <strong id="rejectEmpName"></strong></h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <label class="form-label fw-semibold">Lý do từ chối <span class="text-danger">*</span></label>
                    <textarea name="reject_reason" class="form-control" rows="3" required placeholder="Nhập lý do..."></textarea>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Huỷ</button>
                    <button type="submit" class="btn btn-danger">Xác nhận từ chối</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Modal Chi tiết OT ── -->
<div class="modal fade" id="detailModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-0">
                <h6 class="modal-title">📋 Chi tiết đơn OT</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="detailBody"></div>
        </div>
    </div>
</div>

<!-- ── Modal Xoá 1 đơn OT ── -->
<div class="modal fade" id="deleteOTModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-danger">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                <input type="hidden" name="action"     value="delete_ot">
                <input type="hidden" name="ot_id"      id="deleteOTId">
                <div class="modal-header bg-danger text-white border-0">
                    <h6 class="modal-title fw-bold"><i class="fas fa-trash me-2"></i>Xoá đơn OT</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Xoá đơn OT của: <strong id="deleteOTEmp" class="text-danger"></strong></p>
                    <div class="alert alert-warning py-2 small mb-0">
                        <i class="fas fa-exclamation-triangle me-1"></i>Không thể hoàn tác!
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Huỷ</button>
                    <button type="submit" class="btn btn-danger"><i class="fas fa-trash me-1"></i>Xác nhận xoá</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Modal Xoá hàng loạt OT ── -->
<div class="modal fade" id="bulkDeleteOTModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-danger">
            <div class="modal-header bg-danger text-white border-0">
                <h6 class="modal-title fw-bold"><i class="fas fa-trash-alt me-2"></i>Xoá hàng loạt đơn OT</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Bạn sắp xoá <strong id="bulkOTCountLabel" class="text-danger fs-5"></strong> đơn OT.</p>
                <div class="alert alert-danger py-2 small mb-2">
                    <i class="fas fa-exclamation-circle me-1"></i><strong>Không thể hoàn tác!</strong>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="confirmBulkOT"
                           onchange="document.getElementById('btnConfirmBulkOT').disabled = !this.checked">
                    <label class="form-check-label small fw-semibold text-danger" for="confirmBulkOT">
                        Tôi xác nhận xoá tất cả đơn đã chọn
                    </label>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Huỷ</button>
                <button type="button" id="btnConfirmBulkOT" class="btn btn-danger" disabled onclick="submitBulkDeleteOT()">
                    <i class="fas fa-trash-alt me-1"></i>Xoá tất cả đã chọn
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.btn-xs { padding: 3px 10px; font-size: 12px; }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
// ── Preview file ──
function previewOTFile(input) {
    const box  = document.getElementById('otFilePreviewBox');
    const text = document.getElementById('otFilePreviewText');
    if (!input.files[0]) { box.classList.add('d-none'); return; }
    const f    = input.files[0];
    const size = f.size > 1048576 ? (f.size/1048576).toFixed(2)+' MB' : (f.size/1024).toFixed(1)+' KB';
    text.innerHTML = `<strong>${f.name}</strong> &nbsp;·&nbsp; ${size}
        <br><span class="text-muted">Sẵn sàng import. Nhấn <strong>Import OT ngay</strong>.</span>`;
    box.classList.remove('d-none');
}

// ── Tải file mẫu ──
function downloadOTTemplate() {
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([
        ['ngày', 'mã nhân viên', 'tên', 'số giờ OT'],
        ['02/04/2026', 'DNA24030001', 'Nguyễn Văn A', 3],
        ['02/04/2026', 'DNA24030002', 'Trần Thị B', 2.5],
    ]);
    // Định dạng cột
    ws['!cols'] = [{wch:14},{wch:16},{wch:22},{wch:12}];
    XLSX.utils.book_append_sheet(wb, ws, 'DangKyOT');
    XLSX.writeFile(wb, 'MauDangKyOT.xlsx');
}

// ── Modal từ chối ──
function showRejectModal(id, name) {
    document.getElementById('rejectOtId').value = id;
    document.getElementById('rejectEmpName').textContent = name;
    document.querySelector('#rejectForm textarea').value = '';
    new bootstrap.Modal(document.getElementById('rejectModal')).show();
}

// ── Modal chi tiết ──
function showDetail(ot) {
    const otTypeLabel = { weekday:'Ngày thường', weekend:'Cuối tu��n', holiday:'Ngày lễ' };
    const statusLabel = { pending:'Chờ duyệt', approved:'Đã duyệt', rejected:'Từ chối' };
    document.getElementById('detailBody').innerHTML = `
        <table class="table table-sm">
            <tr><th>Nhân viên</th><td>${ot.full_name} (${ot.employee_code})</td></tr>
            <tr><th>Phòng ban</th><td>${ot.dept_name||'—'}</td></tr>
            <tr><th>Ngày OT</th><td>${ot.ot_date}</td></tr>
            <tr><th>Giờ OT</th><td>${ot.start_time} – ${ot.end_time} (${ot.hours} giờ)</td></tr>
            <tr><th>Loại</th><td>${otTypeLabel[ot.ot_type]||ot.ot_type}</td></tr>
            <tr><th>Lý do</th><td>${ot.reason}</td></tr>
            <tr><th>Trạng thái</th><td>${statusLabel[ot.status]}</td></tr>
            ${ot.approver_name?`<tr><th>Người duyệt</th><td>${ot.approver_name}</td></tr>`:''}
            ${ot.reject_reason?`<tr><th>Lý do từ chối</th><td class="text-danger">${ot.reject_reason}</td></tr>`:''}
        </table>`;
    new bootstrap.Modal(document.getElementById('detailModal')).show();
}

// ── Xoá 1 đơn ──
function confirmDeleteOT(id, name) {
    document.getElementById('deleteOTId').value        = id;
    document.getElementById('deleteOTEmp').textContent = name;
    new bootstrap.Modal(document.getElementById('deleteOTModal')).show();
}

// ── Toggle chọn tất cả ──
function toggleOTAll(cb) {
    document.querySelectorAll('.ot-check').forEach(c => c.checked = cb.checked);
    ['selectAll','selectAllTh'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.checked = cb.checked;
    });
    updateOTBtn();
}

// ── Cập nhật nút hàng loạt ──
function updateOTBtn() {
    const count      = document.querySelectorAll('.ot-check:checked').length;
    const all        = document.querySelectorAll('.ot-check').length;
    const approveBtn = document.getElementById('bulkApproveBtn');
    const deleteBtn  = document.getElementById('btnBulkDeleteOT');
    const bulkCnt    = document.getElementById('bulkCount');
    const delCnt     = document.getElementById('otDeleteCount');

    if (approveBtn) { approveBtn.disabled = count === 0; if (bulkCnt) bulkCnt.textContent = count; }
    if (deleteBtn)  { deleteBtn.disabled  = count === 0; if (delCnt)  delCnt.textContent  = count; }

    ['selectAll','selectAllTh'].forEach(id => {
        const el = document.getElementById(id);
        if (el) { el.indeterminate = count > 0 && count < all; el.checked = count === all && all > 0; }
    });
}

// ── Duyệt hàng loạt ──
function submitBulkApprove() {
    if (!confirm('Duyệt tất cả đơn đã chọn?')) return;
    document.getElementById('otFormAction').value = 'bulk_approve';
    document.getElementById('otForm').submit();
}

// ── Xoá hàng loạt ──
function confirmBulkDeleteOT() {
    const count = document.querySelectorAll('.ot-check:checked').length;
    if (count === 0) return;
    document.getElementById('bulkOTCountLabel').textContent = count;
    document.getElementById('confirmBulkOT').checked = false;
    document.getElementById('btnConfirmBulkOT').disabled = true;
    new bootstrap.Modal(document.getElementById('bulkDeleteOTModal')).show();
}

function submitBulkDeleteOT() {
    document.getElementById('otFormAction').value = 'bulk_delete_ot';
    bootstrap.Modal.getInstance(document.getElementById('bulkDeleteOTModal')).hide();
    document.getElementById('otForm').submit();
}
</script>

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