<?php
session_start();
include 'config.php';

//untuk dapat akses laporan
if (!isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    echo "<div class='alert alert-danger m-3'>Akses ditolak</div>";
    exit;
}

$tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : date('Y-m-d');
$nama    = isset($_GET['nama']) ? $_GET['nama'] : '';
$nama = mysqli_real_escape_string($conn, $nama);

$tgl_dari  = isset($_GET['tgl_dari']) ? $_GET['tgl_dari'] : '';
$tgl_sampai = isset($_GET['tgl_sampai']) ? $_GET['tgl_sampai'] : '';
$lokasi = isset($_GET['lokasi']) ? $_GET['lokasi'] : '';
$lokasi = mysqli_real_escape_string($conn, $lokasi);

//Hitung Total Jam Kerja
function hitungJamKerja($masuk, $pulang)
{
    if (!$masuk || !$pulang) {
        return [
            'text' => '-',
            'total_menit' => 0
        ];
    }

    // convert ke timestamp
    $jamMasuk  = strtotime($masuk);
    $jamPulang = strtotime($pulang);

    // jika pulang lebih kecil dari masuk
    // berarti pindah hari / shift malam
    if ($jamPulang < $jamMasuk) {
        $jamPulang += 86400; // tambah 1 hari
    }

    $selisih = $jamPulang - $jamMasuk;

    $jam = floor($selisih / 3600);
    $menit = floor(($selisih % 3600) / 60);

    return [
        'text' => $jam . ' jam ' . $menit . ' menit',
        'total_menit' => ($jam * 60) + $menit
    ];
}

        $no = 1;
        $sql = "
        SELECT users.nama, absensi.*
        FROM absensi
        JOIN users ON absensi.user_id = users.id
        WHERE 1=1
        ";
        
// Filter tanggal range
if (!empty($tgl_dari) && !empty($tgl_sampai)) {
    $sql .= " AND absensi.tanggal BETWEEN '$tgl_dari' AND '$tgl_sampai'";
} elseif (!empty($tanggal)) {
    // fallback 1 tanggal
    $sql .= " AND absensi.tanggal = '$tanggal'";
}

if (!empty($nama)) {
    $sql .= " AND users.nama LIKE '%$nama%'";
}

if (!empty($lokasi)) {
    $sql .= " AND absensi.lokasi = '$lokasi'";
}

//Rekap untuk memunculkan total status berdasarkan pencarian
$rekapSql = "
SELECT
    SUM(CASE WHEN absensi.status='Hadir' THEN 1 ELSE 0 END) as hadir,
    SUM(CASE WHEN absensi.status='Sakit' THEN 1 ELSE 0 END) as sakit,
    SUM(CASE WHEN absensi.status='Izin' THEN 1 ELSE 0 END) as izin,
    SUM(CASE WHEN absensi.status='Cuti' THEN 1 ELSE 0 END) as cuti,
    SUM(CASE WHEN absensi.status='Alpha' THEN 1 ELSE 0 END) as alpha
FROM absensi
JOIN users ON absensi.user_id = users.id
WHERE 1=1
";

if (!empty($tgl_dari) && !empty($tgl_sampai)) {
    $rekapSql .= " AND absensi.tanggal BETWEEN '$tgl_dari' AND '$tgl_sampai'";
} elseif (!empty($tanggal)) {
    $rekapSql .= " AND absensi.tanggal='$tanggal'";
}

if (!empty($nama)) {
    $rekapSql .= " AND users.nama LIKE '%$nama%'";
}
if (!empty($lokasi)) {
    $rekapSql .= " AND absensi.lokasi = '$lokasi'";
}

$rekapQuery = mysqli_query($conn, $rekapSql);
$rekap = mysqli_fetch_assoc($rekapQuery);

if (!$rekap) {
    $rekap = [
        'hadir' => 0,
        'sakit' => 0,
        'izin'  => 0,
        'cuti'  => 0,
        'alpha' => 0
    ];
}

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Laporan Absensi</title>

    <!-- Bootstrap 5 CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container mt-4">

    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0">Laporan Absensi Karyawan</h5>
        </div>

        <div class="card-body">

            <form method="get" class="row g-3 mb-3">

                <div class="col-md-4">
                    <label class="form-label">Nama Karyawan</label>
                    <input type="text" name="nama" class="form-control"
                        placeholder="Cari nama karyawan"
                        value="<?= htmlspecialchars($_GET['nama'] ?? '') ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Lokasi</label>

                    <select name="lokasi" class="form-select">
                        <option value="">Semua Lokasi</option>

                        <option value="Kantor Pusat"
                            <?= $lokasi=='Kantor Pusat' ? 'selected' : '' ?>>
                            Kantor Pusat
                        </option>

                        <option value="Gudang"
                            <?= $lokasi=='Gudang' ? 'selected' : '' ?>>
                            Gudang
                        </option>

                        <option value="Cabang A"
                            <?= $lokasi=='Cabang A' ? 'selected' : '' ?>>
                            Cabang A
                        </option>

                        <option value="Cabang B"
                            <?= $lokasi=='Cabang B' ? 'selected' : '' ?>>
                            Cabang B
                        </option>

                        <option value="WFH"
                            <?= $lokasi=='WFH' ? 'selected' : '' ?>>
                            WFH
                        </option>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Tanggal Dari</label>
                    <input type="date" name="tgl_dari" class="form-control"
                        value="<?= htmlspecialchars($tgl_dari) ?>">
                </div>

                <div class="col-md-3">
                    <label class="form-label">Tanggal Sampai</label>
                    <input type="date" name="tgl_sampai" class="form-control"
                        value="<?= htmlspecialchars($tgl_sampai) ?>">
                </div>




                <div class="col-md-2 align-self-end">
                    <button type="submit" class="btn btn-primary w-100">
                        Filter
                    </button>
                </div>

                <div class="col-md-2 align-self-end">
                    <a href="laporan.php" class="btn btn-warning w-100">
                        Reset
                    </a>
                </div>

                <div class="col-md-1 align-self-end">
                    <a href="dashboard.php" class="btn btn-secondary w-100">
                        Back
                    </a>
                </div>

            </form>

            <div class="row mb-3">

                <div class="col">
                    <div class="card border-success">
                        <div class="card-body text-center">
                            <h6>Hadir</h6>
                            <h3><?= (int)$rekap['hadir'] ?></h3>
                        </div>
                    </div>
                </div>

                <div class="col">
                    <div class="card border-info">
                        <div class="card-body text-center">
                            <h6>Sakit</h6>
                            <h3><?= (int)$rekap['sakit'] ?></h3>
                        </div>
                    </div>
                </div>

                <div class="col">
                    <div class="card border-warning">
                        <div class="card-body text-center">
                            <h6>Izin</h6>
                            <h3><?= (int)$rekap['izin'] ?></h3>
                        </div>
                    </div>
                </div>

                <div class="col">
                    <div class="card border-primary">
                        <div class="card-body text-center">
                            <h6>Cuti</h6>
                            <h3><?= (int)$rekap['cuti'] ?></h3>
                        </div>
                    </div>
                </div>

                <div class="col">
                    <div class="card border-danger">
                        <div class="card-body text-center">
                            <h6>Alpha</h6>
                            <h3><?= (int)$rekap['alpha'] ?></h3>
                        </div>
                    </div>
                </div>

            </div>

            <div class="col-md-2 align-self-end">
                <a href="export_excel.php?nama=<?= urlencode($nama) ?>&lokasi=<?= urlencode($lokasi) ?>&tgl_dari=<?= urlencode($tgl_dari) ?>&tgl_sampai=<?= urlencode($tgl_sampai) ?>"
                class="btn btn-success">
                Download Excel
                </a>
            </div>


            <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover">
                    <thead class="table-dark text-center">
                        <tr>
                            <th>No</th>
                            <th>Nama</th>
                            <th>Tanggal</th>
                            <th>Jam Masuk</th>
                            <th>Jam Pulang</th>
                            <th>(Total Jam Kerja)</th>
                            <th>Lokasi</th>
                            <th>Foto</th>
                            <th>Foto Pulang</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $query = mysqli_query($conn, $sql);


                        if (mysqli_num_rows($query) > 0) {
                            while ($row = mysqli_fetch_assoc($query)) 
                                {
                                
                        ?>
                        <tr class="text-center">
                            <td><?= $no++ ?></td>
                            <td class="text-start"><?= $row['nama'] ?></td>
                            <td><?= $row['tanggal'] ?></td>
                            <td><?= $row['jam_masuk'] ?? '-' ?></td>
                            <td><?= $row['jam_pulang'] ?? '-' ?></td>
                            <td>
                                <?php
                                    $jamKerja = hitungJamKerja($row['jam_masuk'], $row['jam_pulang']);

                                    if ($jamKerja['text'] == '-') {
                                        echo '-';
                                    } elseif ($jamKerja['total_menit'] > 660) {
                                        // Lebih dari 11 jam → Hijau
                                        echo "<span class='badge bg-success'>
                                                {$jamKerja['text']}
                                            </span>";
                                    } elseif ($jamKerja['total_menit'] < 480) {
                                        // Kurang dari 8 jam → Merah
                                        echo "<span class='badge bg-danger'>
                                                {$jamKerja['text']}
                                            </span>";
                                    } else {
                                        // Antara 8 - 11 jam → Tanpa warna
                                        echo $jamKerja['text'];
                                    }
                                    ?>
                            </td>

                            <td><?= $row['lokasi'] ?></td>
                            <td>
                                <a href="uploads/<?= $row['foto'] ?>" target="_blank">
                                    <img src="uploads/<?= $row['foto'] ?>" width="80" style="cursor:pointer">
                                </a>
                            </td>

                            <td>
                                <?php if($row['foto_pulang']) { ?>
                                    <img src="uploads/<?= $row['foto_pulang'] ?>" width="80">
                                <?php } ?>
                            </td>

                            <td>
                                <span class="badge bg-success">
                                    <?= $row['status'] ?>
                                </span>
                            </td>
                        </tr>
                        <?php
                            }
                        } else {
                        ?>
                        <tr>
                            <td colspan="9" class="text-center text-muted">
                                Data absensi tidak ditemukan
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>

</body>
</html>
