<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$page_title = 'Kelola Kalender Kerja Workshop';
require_once('includes/load.php');
page_require_level(4);

/**
 * Updates the 'hari_kerja_workshop' table with the number of effective work days for a given month and year.
 * This function is crucial for the application's logic.
 *
 * @param int $bulan The month to update (1-12).
 * @param int $tahun The year to update (e.g., 2024).
 */
function update_hari_kerja_tabel_workshop($bulan, $tahun) {
    global $db;

    // 1. Calculate the total days in the given month.
    $total_hari_bulan = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);

    // 2. Count weekends (Sundays only, assuming Saturday is a workday for the workshop).
    $hari_minggu = 0;
    for ($i = 1; $i <= $total_hari_bulan; $i++) {
        $tanggal_sekarang = new DateTime("{$tahun}-{$bulan}-{$i}");
        if ($tanggal_sekarang->format('w') == 0) { // 0 = Sunday
            $hari_minggu++;
        }
    }

    // 3. Count holidays from the kalender_kerja_workshop table.
    $query_libur = "SELECT COUNT(*) AS total_libur FROM kalender_kerja_workshop WHERE status = 'Libur' AND MONTH(tanggal) = '{$bulan}' AND YEAR(tanggal) = '{$tahun}'";
    $result_libur = $db->query($query_libur);
    $data_libur = $db->fetch_assoc($result_libur);
    $jumlah_hari_libur = $data_libur['total_libur'];

    // 4. Calculate the effective work days.
    $hari_kerja_efektif = $total_hari_bulan - $hari_minggu - $jumlah_hari_libur;

    // 5. Update or insert the total effective work days into the 'hari_kerja_workshop' table.
    $query_check = "SELECT id FROM hari_kerja_workshop WHERE bulan = '{$bulan}' AND tahun = '{$tahun}'";
    $result_check = $db->query($query_check);
    
    if ($db->num_rows($result_check) > 0) {
        $query_update = "UPDATE hari_kerja_workshop SET jumlah_hari_kerja = '{$hari_kerja_efektif}', updated_at = NOW() WHERE bulan = '{$bulan}' AND tahun = '{$tahun}'";
        $db->query($query_update);
    } else {
        $query_insert = "INSERT INTO hari_kerja_workshop (bulan, tahun, jumlah_hari_kerja, created_at, updated_at) VALUES ('{$bulan}', '{$tahun}', '{$hari_kerja_efektif}', NOW(), NOW())";
        $db->query($query_insert);
    }
}

// Fetch holiday data from the workshop calendar database table.
$libur_db = find_by_sql("SELECT tanggal, keterangan FROM kalender_kerja_workshop WHERE status = 'Libur'");
$libur_array = [];
foreach ($libur_db as $libur) {
    $libur_array[$libur['tanggal']] = $libur['keterangan'];
}

// Process AJAX requests for adding or deleting holidays.
if (isset($_POST['tanggal']) && isset($_POST['aksi'])) {
    $tanggal = $db->escape($_POST['tanggal']);
    $aksi = $_POST['aksi'];
    $keterangan = $db->escape(isset($_POST['keterangan']) ? $_POST['keterangan'] : '');

    $bulan_perbarui = date('m', strtotime($tanggal));
    $tahun_perbarui = date('Y', strtotime($tanggal));

    if ($aksi == 'tambah') {
        $sql = "INSERT INTO kalender_kerja_workshop (tanggal, status, keterangan, created_at, updated_at) VALUES ('{$tanggal}', 'Libur', '{$keterangan}', NOW(), NOW())";
        if ($db->query($sql)) {
            update_hari_kerja_tabel_workshop($bulan_perbarui, $tahun_perbarui);
            echo json_encode(['status' => 'success', 'pesan' => 'Hari libur berhasil ditambahkan.']);
        } else {
            echo json_encode(['status' => 'error', 'pesan' => 'Gagal menambahkan hari libur. Data mungkin sudah ada.']);
        }
    } elseif ($aksi == 'hapus') {
        $sql = "DELETE FROM kalender_kerja_workshop WHERE tanggal = '{$tanggal}'";
        if ($db->query($sql)) {
            update_hari_kerja_tabel_workshop($bulan_perbarui, $tahun_perbarui);
            echo json_encode(['status' => 'success', 'pesan' => 'Hari libur berhasil dihapus.']);
        } else {
            echo json_encode(['status' => 'error', 'pesan' => 'Gagal menghapus hari libur.']);
        }
    }
    exit;
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-calendar"></span>
                    <span>Kelola Kalender Kerja Workshop</span>
                </strong>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-inline mb-4">
                            <label for="month_select">Pilih Bulan & Tahun:</label>
                            <select id="month_select" class="form-control">
                                <?php for ($m = 1; $m <= 12; $m++): ?>
                                    <option value="<?php echo sprintf('%02d', $m); ?>" <?php echo date('m') == sprintf('%02d', $m) ? 'selected' : ''; ?>>
                                        <?php echo date('F', mktime(0, 0, 0, $m, 10)); ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                            <select id="year_select" class="form-control">
                                <?php for ($y = date('Y'); $y >= date('Y') - 5; $y--): ?>
                                    <option value="<?php echo $y; ?>" <?php echo date('Y') == $y ? 'selected' : ''; ?>>
                                        <?php echo $y; ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div id="calendar_container"></div>
                        <h4 class="mt-4">Total Hari Kerja Efektif: <span id="hari_kerja_total"></span> hari</h4>
                    </div>
                    <div class="col-md-6">
                        <h4>Daftar Hari Libur</h4>
                        <div id="holiday_list" class="list-group">
                        </div>
                        <br>
                        <form id="add_holiday_form" style="display:none;">
                            <div class="form-group">
                                <label for="holiday_date">Tanggal:</label>
                                <input type="text" id="holiday_date" class="form-control" readonly>
                            </div>
                            <div class="form-group">
                                <label for="holiday_desc">Keterangan:</label>
                                <input type="text" id="holiday_desc" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-sm btn-primary">Simpan Libur</button>
                            <button type="button" class="btn btn-sm btn-default" onclick="$('#add_holiday_form').hide();">Batal</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    let holidays = <?php echo json_encode($libur_array); ?>;

    function buildCalendar(month, year) {
        $.ajax({
            url: 'build_calendar.php',
            type: 'GET',
            data: { month: month, year: year, holidays: JSON.stringify(holidays) },
            success: function(response) {
                $('#calendar_container').html(response);
                updateHolidayList(month, year);
                updateHariKerjaCount();
            }
        });
    }

    function updateHariKerjaCount() {
        let month = $('#month_select').val();
        let year = $('#year_select').val();
        let totalDays = new Date(year, month, 0).getDate();
        let weekends = 0;
        
        for (let day = 1; day <= totalDays; day++) {
            let date = new Date(year, month - 1, day);
            if (date.getDay() === 0) { // 0 = Minggu
                weekends++;
            }
        }
        
        let totalHolidays = 0;
        for (let date in holidays) {
            let d = new Date(date);
            if (d.getMonth() + 1 == month && d.getFullYear() == year) {
                totalHolidays++;
            }
        }

        let hariKerja = totalDays - weekends - totalHolidays;
        $('#hari_kerja_total').text(hariKerja);
    }
    
    function updateHolidayList(month, year) {
        $('#holiday_list').empty();
        let hasHolidays = false;
        for (let date in holidays) {
            let d = new Date(date + 'T00:00:00');
            if (d.getMonth() + 1 == month && d.getFullYear() == year) {
                hasHolidays = true;
                $('#holiday_list').append(
                    `<a href="#" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                        <span class="tanggal">${d.getDate()} ${d.toLocaleString('id-ID', { month: 'long' })} ${d.getFullYear()}</span>
                        <span class="keterangan">${holidays[date]}</span>
                        <button type="button" class="btn btn-danger btn-xs delete-holiday" data-tanggal="${date}">
                            <span class="glyphicon glyphicon-trash"></span>
                        </button>
                    </a>`
                );
            }
        }
        if (!hasHolidays) {
              $('#holiday_list').html('<p class="text-muted text-center">Tidak ada hari libur di bulan ini.</p>');
        }
    }

    $(document).on('click', '.day-box', function() {
        let selectedDate = $(this).data('date');
        let selectedDay = $(this).data('day');
        
        if (selectedDay === 0) { // Check only for Sunday
             alert("Tanggal yang Anda pilih adalah hari Minggu.");
             return;
        }

        if (holidays[selectedDate]) {
            if (confirm("Tanggal ini sudah terdaftar sebagai hari libur. Hapus?")) {
                $.post('kalender_kerja_workshop.php', { tanggal: selectedDate, aksi: 'hapus' }, function(response) {
                    let result = JSON.parse(response);
                    if (result.status === 'success') {
                        delete holidays[selectedDate];
                        buildCalendar($('#month_select').val(), $('#year_select').val());
                    }
                    alert(result.pesan);
                });
            }
        } else {
            $('#holiday_date').val(selectedDate);
            $('#add_holiday_form').show();
            $('html, body').animate({
                scrollTop: $("#add_holiday_form").offset().top
            }, 500);
        }
    });

    $('#add_holiday_form').on('submit', function(e) {
        e.preventDefault();
        let tanggal = $('#holiday_date').val();
        let keterangan = $('#holiday_desc').val();
        $.post('kalender_kerja_workshop.php', { tanggal: tanggal, aksi: 'tambah', status: 'Libur', keterangan: keterangan }, function(response) {
            let result = JSON.parse(response);
            if (result.status === 'success') {
                holidays[tanggal] = keterangan;
                buildCalendar($('#month_select').val(), $('#year_select').val());
                $('#add_holiday_form').hide();
                $('#holiday_desc').val('');
            }
            alert(result.pesan);
        });
    });

    $(document).on('click', '.delete-holiday', function() {
        let tanggal = $(this).data('tanggal');
        if (confirm("Apakah Anda yakin ingin menghapus hari libur ini?")) {
            $.post('kalender_kerja_workshop.php', { tanggal: tanggal, aksi: 'hapus' }, function(response) {
                let result = JSON.parse(response);
                if (result.status === 'success') {
                    delete holidays[tanggal];
                    buildCalendar($('#month_select').val(), $('#year_select').val());
                }
                alert(result.pesan);
            });
        }
    });

    $('#month_select, #year_select').on('change', function() {
        buildCalendar($('#month_select').val(), $('#year_select').val());
    });

    buildCalendar($('#month_select').val(), $('#year_select').val());
});
</script>

<?php include_once('layouts/footer.php'); ?>