<?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('production', 'manager', 'director');

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

// ── XỬ LÝ POST ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['request_id'] ?? 0);

    // ── Duyệt / Từ chối ──
    if (in_array($action, ['approved', 'rejected'])) {
        $reason = trim($_POST['reject_reason'] ?? '');
        $stmt   = $pdo->prepare("UPDATE leave_requests SET status=?, approved_by=?, approved_at=NOW(), reject_reason=? WHERE id=? AND status='pending'");
        $stmt->execute([$action, $user['id'], $reason, $id]);

        if ($stmt->rowCount()) {
            $req = $pdo->prepare("SELECT user_id FROM leave_requests WHERE id=?");
            $req->execute([$id]);
            $lr  = $req->fetch();
            $msg = $action === 'approved'
                ? '✅ Đơn xin nghỉ phép của bạn đã được duyệt.'
                : '❌ Đơn xin nghỉ phép bị từ chối: ' . $reason;
            $pdo->prepare("INSERT INTO notifications (user_id, title, message, type, reference_id) VALUES (?, 'Kết quả đơn nghỉ phép', ?, 'leave_request', ?)")
                ->execute([$lr['user_id'], $msg, $id]);
            setFlash('success', 'Đã xử lý đơn nghỉ phép.');
        }
    }

    // ── Xoá 1 đơn (chỉ director) ──
    elseif ($action === 'delete' && $isDirector && $id) {
        $stmt = $pdo->prepare("DELETE FROM leave_requests WHERE id=?");
        $stmt->execute([$id]);
        setFlash($stmt->rowCount() ? 'success' : 'warning',
                 $stmt->rowCount() ? '🗑️ Đã xoá đơn nghỉ phép.' : 'Không tìm thấy đơn.');
    }

    // ── Xoá hàng loạt (chỉ director) ──
    elseif ($action === 'bulk_delete' && $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 leave_requests WHERE id IN ($in)");
            setFlash('success', "🗑️ Đã xoá <strong>{$stmt->rowCount()}</strong> đơn nghỉ phép.");
        }
    }

    header('Location: /erp/modules/attendance/leave_manage.php?filter=' . ($_GET['filter'] ?? 'pending'));
    exit();
}

$filter = $_GET['filter'] ?? 'pending';
$stmt   = $pdo->prepare("
    SELECT lr.*, u.full_name, u.employee_code,
           d.name AS department_name,
           a.full_name AS approver_name
    FROM leave_requests lr
    JOIN users u ON lr.user_id = u.id
    LEFT JOIN departments d ON u.department_id = d.id
    LEFT JOIN users a ON lr.approved_by = a.id
    WHERE (? = 'all' OR lr.status = ?)
    ORDER BY lr.created_at DESC
    LIMIT 100
");
$stmt->execute([$filter, $filter]);
$requests = $stmt->fetchAll();

$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">
        <h4 class="mb-0">📋 Duyệt đơn nghỉ phép</h4>
        <?php if ($isDirector && !empty($requests)): ?>
        <button class="btn btn-danger btn-sm"
                onclick="confirmBulkDeleteLeave()"
                id="btnBulkDeleteLeave" disabled>
            <i class="fas fa-trash-alt me-1"></i>Xoá đã chọn
            <span id="leaveDeleteCount" class="badge bg-white text-danger ms-1">0</span>
        </button>
        <?php endif; ?>
    </div>

    <?php showFlash(); ?>

    <!-- Filter -->
    <div class="btn-group mb-3">
        <a href="?filter=pending"  class="btn btn-sm <?= $filter==='pending'  ?'btn-warning':'btn-outline-warning' ?>">⌛ Chờ duyệt</a>
        <a href="?filter=approved" class="btn btn-sm <?= $filter==='approved' ?'btn-success':'btn-outline-success' ?>">✅ Đã duyệt</a>
        <a href="?filter=rejected" class="btn btn-sm <?= $filter==='rejected' ?'btn-danger':'btn-outline-danger' ?>">❌ Từ chối</a>
        <a href="?filter=all"      class="btn btn-sm <?= $filter==='all'      ?'btn-secondary':'btn-outline-secondary' ?>">Tất cả</a>
    </div>

    <form method="POST" id="leaveForm">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="action"     id="leaveFormAction" value="">

        <div class="card border-0 shadow-sm">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-dark">
                            <tr>
                                <?php if ($isDirector): ?>
                                <th width="40">
                                    <input type="checkbox" class="form-check-input" id="leaveSelectAll"
                                           onchange="toggleLeaveAll(this)">
                                </th>
                                <?php endif; ?>
                                <th>Nhân viên</th>
                                <th>Loại</th>
                                <th>Từ Ngày</th>
                                <th>Đến Ngày</th>
                                <th>Số Ngày</th>
                                <th>Lý do</th>
                                <th>Ngày tạo</th>
                                <th>Trạng thái</th>
                                <th class="text-center">Thao tác</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($requests as $r): ?>
                        <tr>
                            <?php if ($isDirector): ?>
                            <td>
                                <input type="checkbox" name="selected_ids[]" value="<?= $r['id'] ?>"
                                       class="form-check-input leave-check"
                                       onchange="updateLeaveDeleteBtn()">
                            </td>
                            <?php endif; ?>
                            <td>
                                <div class="fw-semibold"><?= htmlspecialchars($r['full_name']) ?></div>
                                <small class="text-muted"><?= $r['employee_code'] ?> &bull; <?= htmlspecialchars($r['department_name'] ?? '') ?></small>
                            </td>
                            <td><?= ['annual'=>'Phép năm','sick'=>'Ốm','unpaid'=>'KL','other'=>'Khác'][$r['leave_type']] ?? $r['leave_type'] ?></td>
                            <td><?= formatDate($r['start_date']) ?></td>
                            <td><?= formatDate($r['end_date']) ?></td>
                            <td><?= $r['total_days'] ?></td>
                            <td><small><?= htmlspecialchars($r['reason']) ?></small></td>
                            <td><small><?= formatDate($r['created_at'], 'd/m H:i') ?></small></td>
                            <td>
                                <?php $badges=['pending'=>'warning','approved'=>'success','rejected'=>'danger'];
                                      $labels=['pending'=>'Chờ','approved'=>'Duyệt','rejected'=>'Từ chối']; ?>
                                <span class="badge bg-<?= $badges[$r['status']] ?>">
                                    <?= $labels[$r['status']] ?>
                                </span>
                            </td>
                            <td class="text-center">
                                <div class="d-flex gap-1 justify-content-center">
                                    <?php if ($r['status'] === 'pending'): ?>
                                    <!-- Duyệt -->
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="csrf_token"  value="<?= $csrf ?>">
                                        <input type="hidden" name="request_id" value="<?= $r['id'] ?>">
                                        <input type="hidden" name="action"     value="approved">
                                        <button class="btn btn-success btn-sm"
                                                onclick="return confirm('Duyệt đơn nghỉ phép này?')"
                                                title="Duyệt">
                                            <i class="fas fa-check"></i>
                                        </button>
                                    </form>
                                    <!-- Từ chối -->
                                    <button class="btn btn-warning btn-sm"
                                            onclick="showRejectLeaveModal(<?= $r['id'] ?>)"
                                            title="Từ chối">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <?php else: ?>
                                    <small class="text-muted"><?= $r['approver_name'] ? htmlspecialchars($r['approver_name']) : '—' ?></small>
                                    <?php endif; ?>

                                    <!-- Xoá — chỉ director -->
                                    <?php if ($isDirector): ?>
                                    <button type="button" class="btn btn-outline-danger btn-sm"
                                            title="Xoá đơn"
                                            onclick="confirmDeleteLeave(<?= $r['id'] ?>, '<?= htmlspecialchars(addslashes($r['full_name'])) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($requests)): ?>
                        <tr>
                            <td colspan="<?= $isDirector ? 10 : 9 ?>" class="text-center text-muted py-4">
                                Không có đơn nào
                            </td>
                        </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </form>

</div>
</div>

<!-- ── Modal Từ chối nghỉ phép ── -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token"  value="<?= $csrf ?>">
                <input type="hidden" name="request_id" id="rejectLeaveId">
                <input type="hidden" name="action"     value="rejected">
                <div class="modal-header">
                    <h6 class="modal-title">❌ Từ chối đơn nghỉ phép</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">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy</button>
                    <button type="submit" class="btn btn-danger">Xác nhận từ chối</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Modal Xoá 1 đơn nghỉ phép ── -->
<div class="modal fade" id="deleteLeaveModal" 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">
                <input type="hidden" name="request_id" id="deleteLeaveId">
                <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 nghỉ phép
                    </h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Xoá đơn nghỉ phép của: <strong id="deleteLeaveEmp" class="text-danger"></strong></p>
                    <div class="alert alert-warning py-2 small mb-0">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        Hành động này <strong>không thể hoàn tác</strong>!
                    </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 nghỉ phép ── -->
<div class="modal fade" id="bulkDeleteLeaveModal" 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 nghỉ phép
                </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="bulkLeaveCountLabel" class="text-danger fs-5"></strong> đơn nghỉ phép.</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> Tất cả đơn được chọn sẽ bị xoá vĩnh viễn.
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="confirmBulkLeave"
                           onchange="document.getElementById('btnConfirmBulkLeave').disabled = !this.checked">
                    <label class="form-check-label small fw-semibold text-danger" for="confirmBulkLeave">
                        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="btnConfirmBulkLeave" class="btn btn-danger" disabled
                        onclick="submitBulkDeleteLeave()">
                    <i class="fas fa-trash-alt me-1"></i>Xoá tất cả đã chọn
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function showRejectLeaveModal(id) {
    document.getElementById('rejectLeaveId').value = id;
    new bootstrap.Modal(document.getElementById('rejectModal')).show();
}

function confirmDeleteLeave(id, name) {
    document.getElementById('deleteLeaveId').value         = id;
    document.getElementById('deleteLeaveEmp').textContent  = name;
    new bootstrap.Modal(document.getElementById('deleteLeaveModal')).show();
}

function toggleLeaveAll(cb) {
    document.querySelectorAll('.leave-check').forEach(c => c.checked = cb.checked);
    updateLeaveDeleteBtn();
}

function updateLeaveDeleteBtn() {
    const count = document.querySelectorAll('.leave-check:checked').length;
    const btn   = document.getElementById('btnBulkDeleteLeave');
    const cnt   = document.getElementById('leaveDeleteCount');
    if (btn) { btn.disabled = count === 0; cnt.textContent = count; }
    const all  = document.querySelectorAll('.leave-check').length;
    const saEl = document.getElementById('leaveSelectAll');
    if (saEl) { saEl.indeterminate = count > 0 && count < all; saEl.checked = count === all && all > 0; }
}

function confirmBulkDeleteLeave() {
    const count = document.querySelectorAll('.leave-check:checked').length;
    if (count === 0) return;
    document.getElementById('bulkLeaveCountLabel').textContent = count;
    document.getElementById('confirmBulkLeave').checked = false;
    document.getElementById('btnConfirmBulkLeave').disabled = true;
    new bootstrap.Modal(document.getElementById('bulkDeleteLeaveModal')).show();
}

function submitBulkDeleteLeave() {
    document.getElementById('leaveFormAction').value = 'bulk_delete';
    bootstrap.Modal.getInstance(document.getElementById('bulkDeleteLeaveModal')).hide();
    document.getElementById('leaveForm').submit();
}
</script>

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