<?php
    include('../loginsession.php');
    error_reporting(E_ALL);
    $filename = basename(__FILE__);
    $save = mysqli_query($conn, "INSERT INTO novia_abc_user_logs (userid,filename) VALUES ('$userini_id','$filename')");
    
//-------------------

    if (isset($_GET['item'])){
        $item = $_GET['item'];
    }
    
    $nilai = 2000;
    
    $today = date("Y-m-d");
    $a = mysqli_fetch_array(mysqli_query($conn, "
    SELECT 
        MAX(tanggal) AS tanggal, 
        COUNT(*) AS total
    FROM novia_abc_user_counter 
    WHERE userid = '$userini_id' 
      AND item = '$item' 
      AND DATE_FORMAT(tanggal, '%Y-%m-%d') = '$today'
    "));
    
        $Total = $a['total'] ?? 0;
        $Hargatotal = $Total*$nilai;

    // MAX(tanggal) → ambil tanggal terbaru sesuai filter.
    // COUNT(*) AS total → hitung jumlah baris yang cocok.
    
//-------------------
    
    $b = mysqli_fetch_array(mysqli_query($conn, "
    SELECT tanggal FROM novia_abc_user_counter 
        WHERE userid='$userini_id' 
        AND item='$item' 
    ORDER BY tanggal DESC 
    LIMIT 1"));
    
        $tanggal_terakhir = isset($b['tanggal']) ? strtotime($b['tanggal']) : 0;
        $tanggal_sekarang = time();
    
        $selisih_detik = $tanggal_terakhir > 0 ? ($tanggal_sekarang - $tanggal_terakhir) : 300000000;
        
    $c = mysqli_fetch_array(mysqli_query($conn, "
    SELECT tanggal FROM novia_abc_user_counter 
        WHERE userid='$userini_id' 
        AND item='$item' 
    ORDER BY tanggal ASC 
    LIMIT 1"));
    
    if (isset($c['tanggal'])) {
        $tanggal_awal = new DateTime($c['tanggal']);
    } else {
        $tanggal_awal = new DateTime();
    }
    $tanggal_awal->modify('-1 day');

?>

<!DOCTYPE html>
<html lang="id">
<head>
	<title>Counter Merokok</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../css/style.css">
	<link href="../images/balance.ico" rel="icon" type="image/icon" />
	
<style>
    /*Style dari Gemini*/
    
    /* =========================================================
       MOSSGREEN PALETTE - Elegant Modern Moss Green
    ========================================================= */
    :root {
        --mossgreen-50:  #f5f7f2;
        --mossgreen-100: #e4eadc;
        --mossgreen-200: #ccd7be;
        --mossgreen-300: #aebe97;
        --mossgreen-400: #8ea36f;
        --mossgreen-500: #728652;
        --mossgreen-600: #5d6e42;
        --mossgreen-700: #4b5936;
        --mossgreen-800: #3d482d;
        --mossgreen-900: #323b25;
        --mossgreen-950: #1e2417;
    }

    body {
        background-color: var(--mossgreen-50);
        background-image: linear-gradient(rgba(245, 247, 242, 0.9), rgba(245, 247, 242, 0.9)), url('../images/Xiaomi5.jpg');
        background-attachment: fixed;
        background-size: cover;
        font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
        color: var(--mossgreen-950);
    }

    /* Navbar / Navigation Button Styling */
    .btn-nav {
        background-color: var(--mossgreen-100);
        color: var(--mossgreen-800);
        border: 1px solid var(--mossgreen-200);
        font-weight: 600;
        transition: all 0.2s ease-in-out;
    }
    .btn-nav:hover {
        background-color: var(--mossgreen-500);
        color: #fff;
    }

    /* Dashboard Counter Cards */
    .counter-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 15px rgba(61, 72, 45, 0.08);
        border: 1px solid var(--mossgreen-100);
    }

    #total {
        font-size: 4rem;
        font-weight: 800;
        color: var(--mossgreen-700);
        line-height: 1;
    }
    
    #timer {
        font-size: 2.2rem;
        font-weight: 700;
        color: var(--mossgreen-900);
        letter-spacing: 2px;
        font-family: monospace, sans-serif;
    }

    /* Main Action Button */
    .btn-smoke {
        background-color: var(--mossgreen-600);
        color: white;
        font-size: 1.3rem;
        font-weight: 700;
        padding: 15px 30px;
        border-radius: 50px;
        border: none;
        box-shadow: 0 4px 12px rgba(93, 110, 66, 0.3);
        transition: all 0.2s ease-in-out;
    }
    .btn-smoke:hover {
        background-color: var(--mossgreen-700);
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(93, 110, 66, 0.4);
        color: white;
    }
    .btn-smoke:active {
        transform: translateY(1px);
    }

    /* Custom Tables inside Cards */
    .card-header-moss {
        background-color: var(--mossgreen-600);
        color: white;
        font-weight: 600;
        border-top-left-radius: 15px !important;
        border-top-right-radius: 15px !important;
    }

    .table thead th {
        background-color: var(--mossgreen-100);
        color: var(--mossgreen-800);
        border-bottom: 2px solid var(--mossgreen-200);
    }

    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgba(228, 234, 220, 0.3);
    }

    /* Form control styling inside table */
    .input-table-time {
        font-size: 0.85rem;
        padding: 0.25rem 0.5rem;
        border: 1px solid var(--mossgreen-200);
        border-radius: 4px;
        text-align: center;
        color: var(--mossgreen-900);
    }
    .input-table-time:focus {
        border-color: var(--mossgreen-500);
        box-shadow: 0 0 0 0.2rem rgba(114, 134, 82, 0.25);
    }
</style>
</head>
<body>

<div class="container my-4" style="max-width: 900px;">
    
    <div class="row g-2 mb-4">
        <div class="col-4">
            <a href="../administrasi.php" class="btn btn-nav w-100 py-2.5 shadow-sm text-decoration-none text-center d-block">NAVIGASI</a>
        </div>
        <div class="col-4">
            <a href="../todo/routine.php" class="btn btn-nav w-100 py-2.5 shadow-sm text-decoration-none text-center d-block">RUTINITAS</a>
        </div>
        <div class="col-4">
            <a href="../aero/meditation.php" class="btn btn-nav w-100 py-2.5 shadow-sm text-decoration-none text-center d-block">MEDITASI</a>
        </div>
    </div>

    <div class="counter-card p-4 text-center mb-4">
        <span class="text-muted text-uppercase fw-bold tracking-wider small d-block mb-1">Hari Ini</span>
        <div id="total" class="mb-2"><?php echo $Total; ?> <span style="font-size: 1.5rem; font-weight:500;">Batang</span></div>
        
        <div class="d-inline-block bg-light px-4 py-2 rounded-pill my-2 border border-light-subtle">
            <span class="text-muted small d-block fw-semibold mb-1">JEDA SEJAK BATANG TERAKHIR</span>
            <div id="timer">00:00:00</div>
        </div>
    </div>

    <div class="text-center mb-4">
        <form method="post" action="">
            <button type="submit" name="submit" class="btn btn-smoke px-5 shadow">
                🔥 MEROKOK LAGI
            </button>
        </form>
    </div>

    <div class="alert text-center fw-bold text-white mb-4 shadow-sm" style="background-color: var(--mossgreen-500); border-radius:12px;">
        Hari Ini: <?php echo $Total; ?> Batang <span class="mx-2">|</span> Estimasi: Rp <?php echo number_format($Hargatotal, 0, ',', '.'); ?>
    </div>

    <?php
    if (isset($_POST['submit'])) {
        $save = mysqli_query($conn, "INSERT INTO novia_abc_user_counter (userid, item) VALUES ('$userini_id', '$item')");
        if ($save) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    title: 'Informasi',
                    text: 'Catatan merokok anda telah di simpan. Anda telah merokok satu batang lagi hari ini.',
                    icon: 'info',
                    confirmButtonColor: '#728652',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location = 'smoking.php?item=$item';
                    }
                });
            </script>";
        }        
    }

    // Pemrosesan aksi Hapus & Update diletakkan sebelum render query agar data langsung ter-refresh
    if (isset($_POST['hapus']) && isset($_POST['idrokok'])) {
        $ID = $_POST['idrokok'];
        $Hapus = mysqli_query($conn, "DELETE FROM novia_abc_user_counter WHERE id = $ID");
        if ($Hapus) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    title: 'Informasi',
                    text: 'Catatan merokok anda telah dihapus.',
                    icon: 'info',
                    confirmButtonColor: '#728652',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location = 'smoking.php?item=$item';
                    }
                });
            </script>";
        }        
    }

    if (isset($_POST['update']) && isset($_POST['idrokok']) && isset($_POST['hariini'])) {
        $ID = $_POST['idrokok'];
        $hariini = $_POST['hariini'];
        $Hariini = new DateTime($hariini);
        $Hariini_formatted = $Hariini->format('Y-m-d H:i:s');
        
        $Update = mysqli_query($conn,"UPDATE novia_abc_user_counter SET tanggal='$Hariini_formatted' WHERE id = $ID");
        if ($Update) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    title: 'Informasi',
                    text: 'Catatan merokok anda telah diperbarui.',
                    icon: 'info',
                    confirmButtonColor: '#728652',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location = 'smoking.php?item=$item';
                    }
                });
            </script>";
        }        
    }

    // Ambil semua data user untuk item ini
    $no = 0;
    $currentDate = (new DateTime())->format('Y-m-d');
    $sql = "SELECT id, tanggal FROM novia_abc_user_counter 
            WHERE userid = $userini_id AND item = '$item' 
            ORDER BY tanggal DESC";
    $result = $conn->query($sql);
    
    $rows = [];
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    ?>

    <div class="card shadow-sm border-0 mb-4" style="border-radius: 15px;">
        <div class="card-header card-header-moss py-3">
            <h5 class="card-title mb-0" style="font-size:1.1rem;">📋 Rincian Batang Hari Ini</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped align-middle mb-0 text-center" style="font-size: 0.95rem;">
                    <thead>
                        <tr>
                            <!-- <th width="8%">No</th> -->
                            <th width="35%">Jam / Waktu</th>
                            <th width="20%">Jeda</th>
                            <th width="37%" colspan="2">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $has_today_data = false;
                    foreach ($rows as $index => $row) {
                        $no++;
                        $currentDateTime = new DateTime($row['tanggal']);
                        $currentDateOnly = $currentDateTime->format('Y-m-d');
                        $timeFormatted = $currentDateTime->format('Y-m-d H:i');
                        
                        $selisihWaktu = '-';
                        if (isset($rows[$index + 1])) {
                            $prevDateTime = new DateTime($rows[$index + 1]['tanggal']);
                            $diff = $prevDateTime->diff($currentDateTime);
                            $selisihMenit = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
                            
                            $jam = floor($selisihMenit / 60);
                            $menit = $selisihMenit % 60;
                            $selisihWaktu = sprintf("%02d:%02d", $jam, $menit);
                        }
                        
                        if ($currentDateOnly == $currentDate) {
                            $has_today_data = true;
                            ?>
                            <tr>
                                <!-- <td><span class="badge bg-secondary rounded-circle"><?php echo $no; ?></span></td> -->
                                <td>
                                    <form method="post" action="" id="form-<?php echo $row['id']; ?>" class="d-flex align-items-center justify-content-center gap-1">
                                        <input type="hidden" name="idrokok" value="<?php echo $row['id']; ?>">
                                        <input type="text" name="hariini" class="form-control form-control-sm text-center input-table-time" value="<?php echo $timeFormatted; ?>" style="max-width: 140px;">
                                </td>
                                <td><strong class="text-dark"><?php echo $selisihWaktu; ?></strong></td>
                                <td>
                                        <button type="submit" name="hapus" class="btn btn-sm btn-outline-danger px-2 py-1" style="font-size:0.8rem;">DEL</button>
                                </td>
                                <td>
                                        <button type="submit" name="update" class="btn btn-sm btn-outline-success px-2 py-1" style="font-size:0.8rem;">UPD</button>
                                    </form>
                                </td>
                            </tr>
                            <?php
                        }
                    }
                    if(!$has_today_data) {
                        echo "<tr><td colspan='5' class='text-muted py-3'>Belum ada data merokok untuk hari ini.</td></tr>";
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>


    <div class="card shadow-sm border-0 mb-4" style="border-radius: 15px;">
        <div class="card-header card-header-moss py-3">
            <h5 class="card-title mb-0" style="font-size:1.1rem;">📅 Catatan 30 Hari Terakhir</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped align-middle mb-0 text-center" style="font-size: 0.95rem;">
                    <thead>
                        <tr>
                            <th>Hari</th>
                            <th>Tanggal</th>
                            <th>Jumlah (Batang)</th>
                            <th>Rupiah</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $se = date('Y-m-d');
                    $sa = new DateTime($se);
                    $sa->modify('-29 day');
                    $sa_formatted = $sa->format('Y-m-d');

                    $period = new DatePeriod(
                        new DateTime($sa_formatted),
                        new DateInterval('P1D'),
                        new DateTime($se . ' +1 day')
                    );

                    $tanggalArray = [];
                    foreach ($period as $date) {
                        $tanggalArray[$date->format('Y-m-d')] = 0;
                    }

                    $query = "SELECT DATE(tanggal) as tanggal, COUNT(*) as total_rokok 
                              FROM novia_abc_user_counter
                              WHERE userid=$userini_id 
                                AND item = $item
                                AND tanggal >= '$sa_formatted'
                              GROUP BY DATE(tanggal)
                              ORDER BY tanggal DESC";
                    $result = $conn->query($query);

                    if ($result && $result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            $tgl = $row['tanggal'];
                            $tanggalArray[$tgl] = $row['total_rokok'];
                        }
                    }
                    $tanggalArray = array_reverse($tanggalArray);

                    $bulan_aero = 0;
                    foreach ($tanggalArray as $tgl => $total_rokok) {
                        $bulan = new DateTime($tgl);
                        $Hari = $bulan->format('l');
                        $hari = isset($HARI[$Hari]) ? $HARI[$Hari] : $Hari; 
                        $bulan_aero += $total_rokok;
                        $harga = $total_rokok * $nilai;
                        
                        if ($bulan->getTimestamp() >= $tanggal_awal->getTimestamp()) {
                            ?>
                            <tr>
                                <td class="text-start ps-4 fw-medium text-secondary"><?php echo $hari; ?></td>
                                <td><?php echo date('d M Y', strtotime($tgl)); ?></td>
                                <td><span class="badge rounded-pill px-3 py-2 bg-light text-dark border"><?php echo $total_rokok; ?></span></td>
                                <td class="text-secondary">Rp <?php echo number_format($harga, 0, ',', '.'); ?></td>
                            </tr>
                            <?php
                        }
                    }
                    $harga_bulan = $bulan_aero * $nilai;
                    ?>
                    </tbody>
                    <tfoot>
                        <tr class="table-success fw-bold text-dark" style="background-color: var(--mossgreen-200) !important;">
                            <td colspan="2" class="text-start ps-4">TOTAL (30 Hari Terakhir)</td>
                            <td><?php echo $bulan_aero; ?> Btg</td>
                            <td>Rp <?php echo number_format($harga_bulan, 0, ',', '.'); ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>


    <div class="card shadow-sm border-0 mb-4" style="border-radius: 15px;">
        <div class="card-header card-header-moss py-3">
            <h5 class="card-title mb-0" style="font-size:1.1rem;">📊 Rekapitulasi per Bulan</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped align-middle mb-0 text-center" style="font-size: 0.95rem;">
                    <thead>
                        <tr>
                            <th colspan="2" class="text-start ps-4">Tahun - Bulan</th>
                            <th>Total Rokok</th>
                            <th>Rupiah</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $tanggal_sekarang_dt = new DateTime(date('Y-m-d'));
                    $bulan_terakhir = date('Y-m');
                    $bulan_array = [];

                    $selisih_bulan = (($tanggal_sekarang_dt->format('Y') - $tanggal_awal->format('Y')) * 12) + ($tanggal_sekarang_dt->format('m') - $tanggal_awal->format('m'));
                    
                    for ($i = 0; $i <= $selisih_bulan; $i++) {
                        $bulan = date('Y-m', strtotime("-$i months", strtotime($bulan_terakhir . "-01")));
                        $bulan_array[$bulan] = 0;
                    }

                    $query_bulan = "SELECT DATE_FORMAT(tanggal, '%Y-%m') as bulan, COUNT(*) as total_rokok_bulan
                                    FROM novia_abc_user_counter
                                    WHERE userid = $userini_id
                                      AND item = $item
                                    GROUP BY DATE_FORMAT(tanggal, '%Y-%m')";
                    
                    $result_bulan = $conn->query($query_bulan);

                    if ($result_bulan && $result_bulan->num_rows > 0) {
                        while ($row = $result_bulan->fetch_assoc()) {
                            $bulan_array[$row['bulan']] = $row['total_rokok_bulan'];
                        }
                    }

                    foreach ($bulan_array as $bulan => $total) {
                        $harga_total = $total * $nilai;
                        ?>
                        <tr>
                            <td colspan="2" class="text-start ps-4 fw-semibold text-dark"><?php echo date('F Y', strtotime($bulan . "-01")); ?></td>
                            <td><span class="badge bg-dark-subtle text-dark px-3 py-2"><?php echo $total; ?> Batang</span></td>
                            <td class="fw-medium text-success">Rp <?php echo number_format($harga_total, 0, ',', '.'); ?></td>
                        </tr>
                        <?php
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // Ambil nilai dari PHP
    let selisih = <?php echo $selisih_detik; ?>;

    function updateTimer() {
        let jam   = Math.floor(selisih / 3600);
        let sisa  = selisih % 3600;
        let menit = Math.floor(sisa / 60);
        let detik = sisa % 60;

        // Format 2 digit
        let format = 
            String(jam).padStart(2, '0') + ":" +
            String(menit).padStart(2, '0') + ":" +
            String(detik).padStart(2, '0');

        document.getElementById("timer").innerText = format;
        selisih++; // tambah 1 detik setiap interval
    }
    
    // Proteksi timer dari data kosong/invalid
    if (<?php echo $selisih_detik; ?> < 300000000) {
        setInterval(updateTimer, 1000);
        updateTimer();
    } else {
        document.getElementById("timer").innerText = "00:00:00";
    }
</script>

</body>
</html>