<?php
session_start();
require("../config.php");
if (!isset($_SESSION['user'])) {
   die("Anda Tidak Memiliki Akses!");
}

function string_date($tanggal, $kostum = false) {
    date_default_timezone_set('Asia/Jakarta');
    
    if ($kostum === false) {
        $inputSeconds = time() - strtotime($tanggal);
    } else {
        $inputSeconds = strtotime($kostum) - strtotime($tanggal);
    }

    $secondsInAMinute = 60;
    $secondsInAnHour = 60 * $secondsInAMinute;
    $secondsInADay = 24 * $secondsInAnHour;
    
    // Extract days
    $days = floor($inputSeconds / $secondsInADay);
    
    // Extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = floor($hourSeconds / $secondsInAnHour);
    
    // Extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = floor($minuteSeconds / $secondsInAMinute);
    
    // Extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = ceil($remainingSeconds);
    
    // Format and return
    $timeParts = [];
    $sections = [
        'Hari' => (int)$days,
        'Jam' => (int)$hours,
        'Menit' => (int)$minutes,
        'Detik' => (int)$seconds,
    ];
    
    foreach ($sections as $name => $value) {
        if ($value > 0) {
            $timeParts[] = $value . ' ' . $name;
        }
    }
    
    return implode(' ', $timeParts);
}

if (isset($_POST['layanan'])) {
    $post_layanan = $conn->real_escape_string($_POST['layanan']);
    $cek_layanan = $conn->query("SELECT * FROM layanan_sosmed WHERE service_id = '$post_layanan' AND status = 'Aktif'");
    
    if (mysqli_num_rows($cek_layanan) == 1) {
        $data_layanan = mysqli_fetch_assoc($cek_layanan);
        $start_time = date('Y-m-d H:i:s');
        
        $qlayanan = $conn->query("SELECT * FROM layanan_sosmed WHERE service_id = '$post_layanan'");
        
        if (mysqli_num_rows($qlayanan) === 1) {
            $flayanan = mysqli_fetch_assoc($qlayanan);
            $riwayat = $conn->query("SELECT * FROM pembelian_sosmed WHERE layanan = '".$flayanan['layanan']."' AND status = 'Success' ORDER BY id DESC LIMIT 10");
            
            if (mysqli_num_rows($riwayat) !== 0) {
                $friwayat = mysqli_fetch_assoc($riwayat);
                $date_cr = $friwayat['date'] . ' ' . $friwayat['time'];
                $date_up = $friwayat['updated_aw'] . ' ' . $friwayat['updated_at'];
                
                // Pastikan kedua tanggal memiliki format yang benar sebelum dihitung
                if (strtotime($date_cr) && strtotime($date_up)) {
                    $selisih = string_date($date_cr, $date_up);
                } else {
                    $selisih = 'Format tanggal tidak valid';
                }
            } else {
                $selisih = 'data tidak cukup';
            }
        } else {
            $selisih = 'data tidak cukup';
        }
        ?>
        
        <label class="col-md-15 control-label">Deskripsi Layanan</label>
        <div class="form-control table-responsive mb-3" style="height:auto !important;" id="note">
            <span><?php echo nl2br($data_layanan['catatan']); ?></span><br />
        </div>
        <input type="hidden" id="start_time" value="<?= $start_time ?>">
        
        <div class="mb-3">
            <label>Waktu Rata-Rata <i class="fa-regular fa-circle-question text-info" data-bs-toggle="modal" data-bs-target="#tooltip"></i></label>
            <input type="text" class="form-control" value="<?= $selisih ?>" readonly>
        </div>
        
        <div class="modal fade" id="tooltip" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h6 id="modalCenterTitle"><em>Waktu rata-rata</em> didasarkan pada 10 pesanan terakhir dengan status pesanan <em>Success</em>.</h6>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                </div>
            </div>
        </div>
        <?php
    } else {
        ?>
        <div class="alert alert-icon alert-danger alert-dismissible fade in" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <i class="mdi mdi-block-helper"></i>
            <b>Gagal :</b> Layanan Tidak Ditemukan
        </div>
        <?php
    }
} else {
    ?>
    <div class="alert alert-icon alert-danger alert-dismissible fade in" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <i class="mdi mdi-block-helper"></i>
        <b>Gagal : </b> Terjadi Kesalahan.
    </div>
    <?php
}
?>