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

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

$periodId = (int)($_GET['period_id'] ?? 0);
if (!$periodId) {
    setFlash('danger', 'Không tìm thấy kỳ lương.');
    header('Location: /erp/modules/payroll/index.php'); exit;
}

// Lấy thông tin kỳ lương
$stmt = $pdo->prepare("
    SELECT pp.*,
           u1.full_name AS created_name,
           u2.full_name AS submitted_name,
           u3.full_name AS approved_name,
           u4.full_name AS locked_name
    FROM payroll_periods pp
    LEFT JOIN users u1 ON pp.created_by   = u1.id
    LEFT JOIN users u2 ON pp.submitted_by = u2.id
    LEFT JOIN users u3 ON pp.approved_by  = u3.id
    LEFT JOIN users u4 ON pp.locked_by    = u4.id
    WHERE pp.id = ?
");
$stmt->execute([$periodId]);
$period = $stmt->fetch();
if (!$period) {
    setFlash('danger', 'Kỳ lương không tồn tại.');
    header('Location: /erp/modules/payroll/index.php'); exit;
}

// Lấy danh sách phiếu lương trong kỳ
$slips = $pdo->prepare("
    SELECT ps.*,
           u.full_name,
           u.email,
           d.name AS department_name,
           ep.has_insurance
    FROM payroll_slips ps
    JOIN users u ON ps.user_id = u.id
    LEFT JOIN employee_profiles ep ON ep.user_id = u.id
    LEFT JOIN departments d ON u.department_id = d.id
    WHERE ps.period_id = ?
    ORDER BY d.name, u.full_name
");
$slips->execute([$periodId]);
$slips = $slips->fetchAll();

// Thống kê tổng
$totalGross   = array_sum(array_column($slips, 'gross_salary'));
$totalNet     = array_sum(array_column($slips, 'net_salary'));
$totalSI      = array_sum(array_column($slips, 'si_employee'));
$totalPIT     = array_sum(array_column($slips, 'pit_amount'));
$totalOT      = array_sum(array_column($slips, 'total_ot_amount'));
$warningCount = count(array_filter($slips, fn($s) => $s['is_late_warning']));

$statusMap = [
    'draft'     => ['secondary', '📝 Nháp'],
    'submitted' => ['warning',   '📤 Chờ duyệt'],
    'approved'  => ['success',   '✅ Đã duyệt'],
    'locked'    => ['dark',      '🔒 Đã lock'],
];
[$sCls, $sLbl] = $statusMap[$period['status']] ?? ['secondary', '?'];
$isLocked = $period['status'] === 'locked';

$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">

    <!-- ── Tiêu đề ── -->
    <div class="d-flex justify-content-between align-items-start mb-4">
        <div>
            <div class="d-flex align-items-center gap-2 mb-1">
                <a href="/erp/modules/payroll/index.php" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <h4 class="mb-0">
                    💰 Bảng lương Tháng <?= $period['period_month'] ?>/<?= $period['period_year'] ?>
                </h4>
                <span class="badge bg-<?= $sCls ?> fs-6"><?= $sLbl ?></span>
            </div>
            <div class="ms-5 text-muted small">
                <?= date('d/m/Y', strtotime($period['period_from'])) ?>
                → <?= date('d/m/Y', strtotime($period['period_to'])) ?>
                &nbsp;·&nbsp; <?= $period['working_days'] ?> ngày công chuẩn
                &nbsp;·&nbsp; <?= count($slips) ?> phiếu lương
                <?php if ($warningCount > 0): ?>
                &nbsp;·&nbsp;
                <span class="text-warning fw-bold">
                    <i class="fas fa-exclamation-triangle"></i> <?= $warningCount ?> cảnh báo về sớm
                </span>
                <?php endif; ?>
            </div>
        </div>
        <div class="d-flex gap-2 flex-wrap justify-content-end">
            <?php if (!$isLocked): ?>
            <button class="btn btn-outline-info btn-sm" onclick="recalcAll(<?= $periodId ?>, this)">
                <i class="fas fa-calculator me-1"></i>Tính lại lương
            </button>
            <?php endif; ?>

            <?php if ($period['status'] === 'draft' && hasRole('accountant','director')): ?>
            <button class="btn btn-warning btn-sm" onclick="doWorkflow(<?= $periodId ?>, 'submit', this)">
                <i class="fas fa-paper-plane me-1"></i>Trình GĐ duyệt
            </button>
            <?php endif; ?>

            <?php if ($period['status'] === 'submitted' && hasRole('director')): ?>
            <button class="btn btn-success btn-sm" onclick="doWorkflow(<?= $periodId ?>, 'approve', this)">
                <i class="fas fa-check me-1"></i>Duyệt
            </button>
            <?php endif; ?>

            <?php if ($period['status'] === 'approved' && hasRole('director')): ?>
            <button class="btn btn-dark btn-sm" onclick="doWorkflow(<?= $periodId ?>, 'lock', this)">
                <i class="fas fa-lock me-1"></i>Lock
            </button>
            <?php endif; ?>

            <?php if ($period['status'] === 'locked' && hasRole('director')): ?>
            <button class="btn btn-outline-secondary btn-sm" onclick="doWorkflow(<?= $periodId ?>, 'reopen', this)">
                <i class="fas fa-lock-open me-1"></i>Mở lại
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?php showFlash(); ?>

    <!-- ── Thống kê tổng ── -->
    <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="text-muted small">Tổng Gross</div>
                <div class="fw-bold fs-5 text-primary"><?= number_format($totalGross, 0, '.', ',') ?>₫</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="text-muted small">Tổng Net (thực nhận)</div>
                <div class="fw-bold fs-5 text-success"><?= number_format($totalNet, 0, '.', ',') ?>₫</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="text-muted small">Tổng BHXH NV đóng</div>
                <div class="fw-bold fs-5 text-warning"><?= number_format($totalSI, 0, '.', ',') ?>₫</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="card border-0 shadow-sm text-center py-3">
                <div class="text-muted small">Tổng Thuế TNCN</div>
                <div class="fw-bold fs-5 text-danger"><?= number_format($totalPIT, 0, '.', ',') ?>₫</div>
            </div>
        </div>
    </div>

    <!-- ── Bảng danh sách phiếu ── -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-0 pt-3 d-flex justify-content-between align-items-center">
            <h6 class="fw-bold mb-0">📋 Danh sách phiếu lương</h6>
            <div class="d-flex gap-2">
                <input type="text" id="searchInput" class="form-control form-control-sm"
                       placeholder="🔍 Tìm tên nhân viên..." style="width:220px"
                       onkeyup="filterTable()">
            </div>
        </div>
        <div class="card-body p-0">
            <?php if (empty($slips)): ?>
            <div class="text-center text-muted py-5">
                <i class="fas fa-users fa-3x mb-3 d-block opacity-25"></i>
                <p class="mb-2">Chưa có phiếu lương nào.</p>
                <?php if (!$isLocked): ?>
                <button class="btn btn-primary btn-sm" onclick="recalcAll(<?= $periodId ?>, this)">
                    <i class="fas fa-calculator me-1"></i>Tính lương ngay
                </button>
                <?php endif; ?>
            </div>
            <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0 align-middle" id="slipTable">
                    <thead class="table-dark" style="font-size:12px">
                        <tr>
                            <th>#</th>
                            <th>Nhân viên</th>
                            <th>Phòng ban</th>
                            <th class="text-center">Ngày công</th>
                            <th class="text-center">Nghỉ KL</th>
                            <th class="text-end">Lương CB</th>
                            <th class="text-end">OT</th>
                            <th class="text-end">Gross</th>
                            <th class="text-end">BHXH</th>
                            <th class="text-end">Thuế TNCN</th>
                            <th class="text-end text-success fw-bold">Thực nhận</th>
                            <th class="text-center">Cảnh báo</th>
                            <th class="text-center">Thao tác</th>
                        </tr>
                    </thead>
                    <tbody style="font-size:13px">
                    <?php foreach ($slips as $i => $s): ?>
                    <tr class="<?= $s['is_late_warning'] ? 'table-warning' : '' ?>">
                        <td class="text-muted"><?= $i + 1 ?></td>
                        <td>
                            <div class="fw-semibold"><?= htmlspecialchars($s['full_name']) ?></div>
                            <div class="text-muted" style="font-size:11px"><?= htmlspecialchars($s['email'] ?? '') ?></div>
                            <?php if ($s['manually_adjusted']): ?>
                            <span class="badge bg-info" style="font-size:10px">
                                <i class="fas fa-pen"></i> Đã chỉnh tay
                            </span>
                            <?php endif; ?>
                        </td>
                        <td class="text-muted small"><?= htmlspecialchars($s['department_name'] ?? '—') ?></td>
                        <td class="text-center">
                            <span class="fw-semibold"><?= number_format($s['total_paid_days'], 1) ?></span>
                            <span class="text-muted">/<?= $s['working_days_standard'] ?></span>
                        </td>
                        <td class="text-center">
                            <?php if ($s['unpaid_leave_days'] > 0): ?>
                            <span class="badge bg-danger"><?= $s['unpaid_leave_days'] ?> ngày</span>
                            <?php else: ?>
                            <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end"><?= number_format($s['basic_salary_received'], 0, '.', ',') ?></td>
                        <td class="text-end">
                            <?php if ($s['total_ot_amount'] > 0): ?>
                            <span class="text-info"><?= number_format($s['total_ot_amount'], 0, '.', ',') ?></span>
                            <?php else: ?>
                            <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end fw-semibold"><?= number_format($s['gross_salary'], 0, '.', ',') ?></td>
                        <td class="text-end text-warning">
                            <?= $s['has_insurance'] ? number_format($s['si_employee'], 0, '.', ',') : '<span class="text-muted">—</span>' ?>
                        </td>
                        <td class="text-end text-danger">
                            <?= $s['pit_amount'] > 0 ? number_format($s['pit_amount'], 0, '.', ',') : '<span class="text-muted">—</span>' ?>
                        </td>
                        <td class="text-end fw-bold text-success">
                            <?= number_format($s['net_salary'], 0, '.', ',') ?>
                        </td>
                        <td class="text-center">
                            <?php if ($s['is_late_warning']): ?>
                            <span class="badge bg-warning text-dark" title="<?= htmlspecialchars($s['late_warning_note'] ?? '') ?>">
                                <i class="fas fa-exclamation-triangle"></i> Về sớm
                            </span>
                            <?php else: ?>
                            <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <div class="d-flex gap-1 justify-content-center">
                                <a href="/erp/modules/payroll/slip_edit.php?id=<?= $s['id'] ?>"
                                   class="btn btn-xs btn-outline-primary" title="Xem/Sửa">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="/erp/modules/payroll/slip_print.php?id=<?= $s['id'] ?>"
                                   target="_blank"
                                   class="btn btn-xs btn-outline-secondary" title="In phiếu">
                                    <i class="fas fa-print"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                    <tfoot class="table-secondary fw-bold" style="font-size:13px">
                        <tr>
                            <td colspan="5" class="text-end">TỔNG CỘNG:</td>
                            <td class="text-end"><?= number_format(array_sum(array_column($slips,'basic_salary_received')), 0, '.', ',') ?></td>
                            <td class="text-end text-info"><?= number_format($totalOT, 0, '.', ',') ?></td>
                            <td class="text-end"><?= number_format($totalGross, 0, '.', ',') ?></td>
                            <td class="text-end text-warning"><?= number_format($totalSI, 0, '.', ',') ?></td>
                            <td class="text-end text-danger"><?= number_format($totalPIT, 0, '.', ',') ?></td>
                            <td class="text-end text-success"><?= number_format($totalNet, 0, '.', ',') ?></td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── Timeline trạng thái ── -->
    <div class="card border-0 shadow-sm mt-4">
        <div class="card-header bg-white border-0 pt-3">
            <h6 class="fw-bold mb-0">📌 Lịch sử xử lý</h6>
        </div>
        <div class="card-body">
            <div class="d-flex gap-4 flex-wrap">
                <div class="d-flex align-items-center gap-2">
                    <div class="rounded-circle bg-success d-flex align-items-center justify-content-center text-white"
                         style="width:32px;height:32px;font-size:12px">
                        <i class="fas fa-plus"></i>
                    </div>
                    <div>
                        <div class="fw-semibold small">Tạo kỳ lương</div>
                        <div class="text-muted" style="font-size:11px">
                            <?= date('d/m/Y H:i', strtotime($period['created_at'])) ?>
                            · <?= htmlspecialchars($period['created_name'] ?? '') ?>
                        </div>
                    </div>
                </div>

                <?php if ($period['submitted_at']): ?>
                <div class="text-muted align-self-center">→</div>
                <div class="d-flex align-items-center gap-2">
                    <div class="rounded-circle bg-warning d-flex align-items-center justify-content-center"
                         style="width:32px;height:32px;font-size:12px">
                        <i class="fas fa-paper-plane"></i>
                    </div>
                    <div>
                        <div class="fw-semibold small">Trình duyệt</div>
                        <div class="text-muted" style="font-size:11px">
                            <?= date('d/m/Y H:i', strtotime($period['submitted_at'])) ?>
                            · <?= htmlspecialchars($period['submitted_name'] ?? '') ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($period['approved_at']): ?>
                <div class="text-muted align-self-center">→</div>
                <div class="d-flex align-items-center gap-2">
                    <div class="rounded-circle bg-success d-flex align-items-center justify-content-center text-white"
                         style="width:32px;height:32px;font-size:12px">
                        <i class="fas fa-check"></i>
                    </div>
                    <div>
                        <div class="fw-semibold small">Đã duyệt</div>
                        <div class="text-muted" style="font-size:11px">
                            <?= date('d/m/Y H:i', strtotime($period['approved_at'])) ?>
                            · <?= htmlspecialchars($period['approved_name'] ?? '') ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($period['locked_at']): ?>
                <div class="text-muted align-self-center">→</div>
                <div class="d-flex align-items-center gap-2">
                    <div class="rounded-circle bg-dark d-flex align-items-center justify-content-center text-white"
                         style="width:32px;height:32px;font-size:12px">
                        <i class="fas fa-lock"></i>
                    </div>
                    <div>
                        <div class="fw-semibold small">Đã lock</div>
                        <div class="text-muted" style="font-size:11px">
                            <?= date('d/m/Y H:i', strtotime($period['locked_at'])) ?>
                            · <?= htmlspecialchars($period['locked_name'] ?? '') ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

</div>
</div>

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

<script>
function filterTable() {
    const q = document.getElementById('searchInput').value.toLowerCase();
    document.querySelectorAll('#slipTable tbody tr').forEach(row => {
        row.style.display = row.innerText.toLowerCase().includes(q) ? '' : 'none';
    });
}

async function recalcAll(periodId, btn) {
    if (!confirm('Tính lại lương cho tất cả nhân viên?\n⚠️ Phiếu đã điều chỉnh tay sẽ giữ nguyên phần nhập tay.')) return;
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Đang tính...';
    try {
        const res  = await fetch('/erp/api/payroll/calculate.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ period_id: periodId })
        });
        const data = await res.json();
        alert(data.msg + (data.errors?.length ? '\n\nLỗi:\n' + data.errors.join('\n') : ''));
        if (data.ok) location.reload();
        else { btn.disabled = false; btn.innerHTML = orig; }
    } catch(e) {
        alert('Lỗi kết nối!');
        btn.disabled = false; btn.innerHTML = orig;
    }
}

async function doWorkflow(periodId, action, btn) {
    const labels = {
        submit:  'Trình Giám đốc duyệt kỳ lương này?',
        approve: '✅ Duyệt kỳ lương?\nNhân viên sẽ thấy phiếu lương sau khi duyệt.',
        lock:    '🔒 Lock kỳ lương?\nSau khi lock sẽ không thể chỉnh sửa.',
        reopen:  '🔓 Mở lại kỳ lương để chỉnh sửa?'
    };
    if (!confirm(labels[action] || 'Xác nhận?')) return;
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    try {
        const res  = await fetch('/erp/api/payroll/workflow.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ period_id: periodId, action })
        });
        const data = await res.json();
        if (data.ok) { alert(data.msg); location.reload(); }
        else { alert('❌ ' + data.msg); btn.disabled = false; btn.innerHTML = orig; }
    } catch(e) {
        alert('Lỗi kết nối!');
        btn.disabled = false; btn.innerHTML = orig;
    }
}
</script>

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