<?php
session_start();
if (empty($_SESSION['SESSION_USER']) && empty($_SESSION['SESSION_ID'])) {
    header('location:../../login/');
    exit;
} else {
    require_once '../../../library/sw-config.php';
    require_once '../../login/login_session.php';
    include('../../../library/sw-function.php');

    switch (@$_GET['action']) {

        /* -------  LOAD DATA ABSENSI ----------*/
        case 'absensi':
            $error = [];

            // Validasi ID
            if (empty($_GET['id'])) {
                $error[] = 'ID tidak boleh kosong';
            } else {
                $id = mysqli_real_escape_string($connection, $_GET['id']);
            }

            // Ambil bulan & tahun
            if (!empty($_POST['month']) && !empty($_POST['year'])) {
                $bulan = $_POST['month'];
                $tahun = $_POST['year'];
            } else {
                $bulan = date("m");
                $tahun = date("Y");
            }

            $hari       = date("d");
            $jumlahhari = date("t", mktime(0, 0, 0, $bulan, $hari, $tahun));
            $s          = date("w", mktime(0, 0, 0, $bulan, 1, $tahun));

            if (empty($error)) {
                echo '
                <div class="table-responsive">
                <table class="table table-bordered table-hover" id="swdatatable">
                    <thead>
                        <tr>
                            <th class="align-middle" width="20">No</th>
                            <th class="align-middle">Tanggal</th>
                            <th class="align-middle text-center"><i class="fa fa-picture-o"></i></th>
                            <th class="align-middle text-center">Jam Masuk</th>
                            <th class="align-middle text-center"><i class="fa fa-picture-o"></i></th>
                            <th class="align-middle text-center">Jam Pulang</th>
                            <th class="align-middle text-center">Lokasi</th>
                            <th class="align-middle">Status</th>
                            <th class="align-middle text-right">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>';

                for ($d = 1; $d <= $jumlahhari; $d++) {
                    $warna         = '';
                    $background    = '';
                    $status_hadir  = 'Tidak Hadir';

                    if (date("l", mktime(0, 0, 0, $bulan, $d, $tahun)) == "Sunday") {
                        $warna        = '#ffffff';
                        $background   = '#005CAA';
                        $status_hadir = 'Libur Akhir Pekan';
                    }

                    $date_month_year = $tahun . '-' . $bulan . '-' . $d;

                    // Filter data absensi
                    $filter = "employees_id='$id' AND presence_date='$date_month_year' AND MONTH(presence_date)='$bulan' AND year(presence_date)='$tahun'";

                    // Ambil data shift karyawan
                    $query  = "SELECT employees.id, shift.shift_id, shift.time_in, shift.time_out 
                               FROM employees, shift 
                               WHERE employees.shift_id=shift.shift_id AND employees.id='$id'";
                    $result = $connection->query($query);
                    $row    = $result->fetch_assoc();

                    $shift_time_in = $row['time_in'];
                    $newtimestamp  = date('H:i:s', strtotime("$shift_time_in + 5 minute"));

                    // Data absensi
                    $query_absen = "SELECT presence_id, presence_date, time_in, time_out, picture_in, picture_out, 
                                           present_id, presence_address, information, 
                                           TIMEDIFF(TIME(time_in),'$shift_time_in') AS selisih,
                                           IF (time_in>'$shift_time_in','Telat',
                                               IF(time_in='00:00:00','Tidak Masuk','Tepat Waktu')) AS status 
                                    FROM presence 
                                    WHERE $filter ORDER BY presence_id DESC";
                    $result_absen = $connection->query($query_absen);
                    $row_absen    = $result_absen->fetch_assoc();

                    // Status kehadiran
                    $status_label = '';
                    if (empty($row_absen['time_in'])) {
                        $status_hadir = (date("l", mktime(0, 0, 0, $bulan, $d, $tahun)) == "Sunday")
                            ? 'Libur Akhir Pekan'
                            : '<span class="label label-danger">Tidak Hadir</span>';
                    } else {
                        $querya  = "SELECT present_name FROM present_status WHERE present_id='{$row_absen['present_id']}'";
                        $resulta = $connection->query($querya);
                        $rowa    = $resulta->fetch_assoc();
                        $status_hadir = '<label class="label label-warning">' . $rowa['present_name'] . '</label>';
                    }

                    // Status Jam Masuk
                    if ($row_absen['status'] == 'Telat') {
                        $status_label = '<label class="label label-danger">Telat</label>';
                    } elseif ($row_absen['status'] == 'Tepat Waktu') {
                        $status_label = '<label class="label label-info">Tepat Waktu</label>';
                    } else {
                        $status_label = '<label class="label label-danger">Tidak Masuk</label>';
                    }

                    // Lokasi
                    list($latitude, $longitude) = explode(',', $row_absen['presence_address']);

                    echo '
                    <tr style="background:' . $background . ';color:' . $warna . '">
                        <td class="text-center">' . $d . '</td>
                        <td>' . format_hari_tanggal($date_month_year) . '</td>';

                    // Foto & jam masuk
                    if ($row_absen['picture_in']) {
                        echo '<td class="text-center picture"><a class="image-link" href="' . $site_url . '/content/present/' . $row_absen['picture_in'] . '" target="_blank">
                                <img src="../timthumb?src=' . $site_url . '/content/present/' . $row_absen['picture_in'] . '&h=40&w=40"></a></td>';
                    } else {
                        echo '<td class="text-center"><img src="../timthumb?src=' . $site_url . '/content/avatar.jpg&h=40&w=40"></td>';
                    }
                    echo '<td>' . $row_absen['time_in'] . '</td>';

                    // Foto & jam pulang
                    if ($row_absen['picture_out']) {
                        echo '<td class="text-center picture"><a class="image-link" href="' . $site_url . '/content/present/' . $row_absen['picture_out'] . '" target="_blank">
                                <img src="../timthumb?src=' . $site_url . '/content/present/' . $row_absen['picture_out'] . '&h=40&w=40"></a></td>';
                    } else {
                        echo '<td class="text-center"><img src="../timthumb?src=' . $site_url . '/content/avatar.jpg&h=40&w=40"></td>';
                    }
                    echo '<td>' . $row_absen['time_out'] . '</td>';

                    echo '
                        <td><p class="btn-modal" data-latitude="' . $latitude . '" data-longitude="' . $longitude . '">Lat: ' . $latitude . '<br>Long: ' . $longitude . '</p></td>
                        <td>' . $status_hadir . ' ' . $status_label . '<br>' . $row_absen['information'] . '</td>
                        <td class="text-right">
                            <button type="button" class="btn btn-warning btn-xs btn-modal enable-tooltip" title="Lokasi" 
                                data-latitude="' . $latitude . '" data-longitude="' . $longitude . '">
                                <i class="fa fa-map-marker"></i> Lokasi
                            </button>
                        </td>
                    </tr>';
                }

                echo '
                    </tbody>
                </table>
                </div>';

                // Statistik absensi
                $filter = "employees_id='$id' AND MONTH(presence_date)='$bulan' AND year(presence_date)='$tahun'";

                $hadir = $connection->query("SELECT presence_id FROM presence WHERE $filter AND present_id='1'");
                $sakit = $connection->query("SELECT presence_id FROM presence WHERE $filter AND present_id='2'");
                $izin  = $connection->query("SELECT presence_id FROM presence WHERE $filter AND present_id='3'");
                $telat = $connection->query("SELECT presence_id FROM presence WHERE $filter AND time_in>'$shift_time_in'");

                echo '
                <hr>
                <div class="row">
                    <div class="col-md-3"><p>Hadir : <span class="label label-success">' . $hadir->num_rows . '</span></p></div>
                    <div class="col-md-3"><p>Telat : <span class="label label-danger">' . $telat->num_rows . '</span></p></div>
                    <div class="col-md-3"><p>Sakit : <span class="label label-warning">' . $sakit->num_rows . '</span></p></div>
                    <div class="col-md-3"><p>Izin : <span class="label label-info">' . $izin->num_rows . '</span></p></div>
                </div>';

                echo '
                <script>
                    $("#swdatatable").dataTable({
                        "iDisplayLength": 35,
                        "aLengthMenu": [[35, 40, 50, -1], [35, 40, 50, "All"]]
                    });
                    $(".image-link").magnificPopup({type:"image"});
                </script>
                <script>
                    $(function () {
                        $(\'[data-toggle="tooltip"]\').tooltip()
                    });
                </script>';
            } else {
                echo 'Data tidak ditemukan';
            }
        break;
    }
}
