<?php
require_once 'includes/header.php';

if (!canView('hr_reports')) {
    echo "<div class='alert alert-danger'>ليس لديك صلاحية للوصول إلى هذه الصفحة.</div>";
    require_once 'includes/footer.php';
    exit;
}

$report_type = $_GET['type'] ?? 'attendance_summary';
$month = $_GET['month'] ?? date('m');
$year = $_GET['year'] ?? date('Y');

?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">تقارير الموارد البشرية</h1>
    <div class="btn-toolbar mb-2 mb-md-0 d-print-none">
        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="window.print()">
            <i class="fas fa-print"></i> طباعة
        </button>
    </div>
</div>

<div class="row d-print-none mb-4">
    <div class="col-md-12">
        <ul class="nav nav-tabs">
            <li class="nav-item">
                <a class="nav-link <?= $report_type == 'attendance_summary' ? 'active' : '' ?>" href="?type=attendance_summary">ملخص الحضور الشهري</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?= $report_type == 'employee_list' ? 'active' : '' ?>" href="?type=employee_list">قائمة الموظفين الشاملة</a>
            </li>
        </ul>
    </div>
</div>

<!-- Filters -->
<?php if ($report_type == 'attendance_summary'): ?>
<div class="card shadow-sm mb-4 d-print-none">
    <div class="card-body">
        <form class="row g-3 align-items-end" method="get">
            <input type="hidden" name="type" value="attendance_summary">
            <div class="col-md-3">
                <label class="form-label">الشهر</label>
                <select name="month" class="form-select">
                    <?php for($m=1; $m<=12; $m++): ?>
                    <option value="<?= $m ?>" <?= $m == $month ? 'selected' : '' ?>><?= date('F', mktime(0, 0, 0, $m, 1)) ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">السنة</label>
                <select name="year" class="form-select">
                    <?php for($y=date('Y')-1; $y<=date('Y')+1; $y++): ?>
                    <option value="<?= $y ?>" <?= $y == $year ? 'selected' : '' ?>><?= $y ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">عرض التقرير</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-white">
        <h5 class="mb-0">تقرير الحضور لشهر <?= $month ?> / <?= $year ?></h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped text-center">
                <thead>
                    <tr>
                        <th class="text-start">الموظف</th>
                        <th>أيام الحضور</th>
                        <th>أيام الغياب</th>
                        <th>التأخير</th>
                        <th>إجازات</th>
                        <th>نسبة الحضور</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT e.id, e.first_name, e.last_name,
                            COUNT(CASE WHEN a.status = 'present' THEN 1 END) as present_days,
                            COUNT(CASE WHEN a.status = 'absent' THEN 1 END) as absent_days,
                            COUNT(CASE WHEN a.status = 'late' THEN 1 END) as late_days,
                            COUNT(CASE WHEN a.status = 'excused' OR a.status = 'holiday' THEN 1 END) as leave_days
                            FROM hr_employees e
                            LEFT JOIN hr_attendance a ON e.id = a.employee_id 
                                AND MONTH(a.date) = ? AND YEAR(a.date) = ?
                            WHERE e.status = 'active'
                            GROUP BY e.id
                            ORDER BY e.first_name";
                    $stmt = db()->prepare($sql);
                    $stmt->execute([$month, $year]);
                    $report_data = $stmt->fetchAll();

                    foreach ($report_data as $row):
                        $total_days_recorded = $row['present_days'] + $row['absent_days'] + $row['late_days'] + $row['leave_days'];
                        $attendance_rate = $total_days_recorded > 0 
                            ? round((($row['present_days'] + $row['late_days']) / $total_days_recorded) * 100, 1) 
                            : 0;
                    ?>
                    <tr>
                        <td class="text-start fw-bold"><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></td>
                        <td class="text-success"><?= $row['present_days'] ?></td>
                        <td class="text-danger"><?= $row['absent_days'] ?></td>
                        <td class="text-warning"><?= $row['late_days'] ?></td>
                        <td class="text-info"><?= $row['leave_days'] ?></td>
                        <td class="fw-bold"><?= $attendance_rate ?>%</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php elseif ($report_type == 'employee_list'): ?>
    <div class="card shadow-sm">
        <div class="card-header bg-white">
            <h5 class="mb-0">سجل الموظفين الشامل</h5>
        </div>
        <div class="card-body">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>الرقم الوظيفي</th>
                        <th>الاسم</th>
                        <th>القسم</th>
                        <th>الوظيفة</th>
                        <th>تاريخ التعيين</th>
                        <th>الراتب الأساسي</th>
                        <th>رقم الهاتف</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $employees = db()->query("SELECT e.*, d.name as dept_name FROM hr_employees e LEFT JOIN hr_departments d ON e.department_id = d.id WHERE e.status = 'active' ORDER BY e.id")->fetchAll();
                    foreach ($employees as $emp):
                    ?>
                    <tr>
                        <td>#<?= $emp['id'] ?></td>
                        <td><?= htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']) ?></td>
                        <td><?= htmlspecialchars($emp['dept_name'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($emp['job_title']) ?></td>
                        <td><?= $emp['join_date'] ?></td>
                        <td><?= number_format($emp['basic_salary'], 2) ?></td>
                        <td><?= htmlspecialchars($emp['phone']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<style>
    @media print {
        .d-print-none { display: none !important; }
        .sidebar, .top-navbar { display: none !important; }
        .main-content { margin: 0 !important; padding: 0 !important; }
        .card { border: none !important; shadow: none !important; }
    }
</style>

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