<?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'];
        $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 = strtotime($b['tanggal']);
        $tanggal_sekarang = time();
    
        $selisih_detik = $tanggal_sekarang - $tanggal_terakhir;
        //if ($selisih_detik == 0) $selisih_detik = 1;
        
    $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"));
    $tanggal_awal = new DateTime($c['tanggal']);
    $tanggal_awal->modify('-1 day');

?>

<!DOCTYPE html>
<html lang="id">
<head>
	<title>Counter</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="../css/style.css">
	<link href="../images/balance.ico" rel="icon" type="image/icon" />
	
<style>
    body {
    margin: auto;
    background-color: #fff;
    background-image : url('../images/Xiaomi5.jpg');
    max-width: 900px;
    }
    #timer {
      font-size: 39px;       /* ukuran huruf */
      text-align: center;    /* teks di dalam div rata tengah */
      margin: 0 auto;        /* div berada di tengah */
      width: fit-content;    /* lebar mengikuti isi */
    }    
    #total {
      font-size: 58px;       /* ukuran huruf */
      text-align: center;    /* teks di dalam div rata tengah */
      margin: 0 auto;        /* div berada di tengah */
      width: fit-content;    /* lebar mengikuti isi */
    }    

</style>
</head>
<body>
    <table width="100%" cellpadding="5">
		<tr class="satu"><td colspan="4"></td></tr>
		<tr class="dua">
			<td><a href="../administrasi.php" title="Reset Data Kelurahan"><button style="padding : 10px; width:100%; background-color:#A6B7C1;">NAVIGASI</button></a></td>
			<td><a href="../todo/routine.php" title="User Log"><button style="padding : 10px; width:100%; background-color:#A6B7C1;"> PDA </button></a></td>
			<td><a href="../aero/meditation.php" title="Meditasi"><button style="padding : 10px; width:100%; background-color:#A6B7C1;">MEDITASI</button></a></td>
		</tr>
		<tr class="satu"><td colspan="4"></td></tr>
	</table>
	<br>
	    <div id="total">
            <?php echo "$Total"; ?>
        </div>
        <br>	    
        <div id="timer"></div>
	    <br>

    <div style="text-align: center;">
    <form method="post" action="">
        <input type="submit" name="submit" value="MEROKOK LAGI" style="font-size: 27px;">
    </form>
    </div>
    <br>

<br>
<table width="100%" cellpadding="5">
        <tr class="satu">
            <td colspan="5"><button style="padding : 10px; width:100%; background-color:#B6B7C1;">
                Hari Ini <?php echo "$Total"; ?> Batang (Rp <?php echo "$Hargatotal"; ?>)
                </button></td>
        </tr>
		<tr class="satu">
		    <th>No</th>
		    <th>Jam</th>
		    <th>Jeda</th>
    		<th>Hapus</th>
    		<th>Update</th>
		</tr>

    
<?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',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location = 'smoking.php?item=$item';
                    }
                });
            </script>";
        }        
    }
//Deepseek
    $no = 0;
    $currentDate = (new DateTime())->format('Y-m-d');
    
    // Ambil semua data user untuk item 1
    $sql = "SELECT id, tanggal FROM novia_abc_user_counter 
            WHERE userid = $userini_id AND item = '1' 
            ORDER BY tanggal DESC";
    $result = $conn->query($sql);
    
    $rows = [];
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    
    // Proses data untuk menghitung selisih menit dengan baris sebelumnya
    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');
        
        // Hitung selisih menit dengan baris sebelumnya (index+1 karena DESC)
        $selisihMenit = '';
        $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;
            
            // Konversi ke format jam:menit
            $jam = floor($selisihMenit / 60);
            $menit = $selisihMenit % 60;
            $selisihWaktu = sprintf("%02d:%02d", $jam, $menit);
            
        }
        
        // Hanya tampilkan data yang tanggalnya sama dengan hari ini
        if ($currentDateOnly == $currentDate) {
            ?>
            <form method="post" action="">
                <input type="hidden" name="idrokok" value="<?php echo $row['id']; ?>">
                <tr class="dua">
                    <td align="center"><?php echo $no; ?></td>
                    <td align="center"><input type="text" name="hariini" size="12" value="<?php echo $timeFormatted; ?>" style="font-size: 12px;"></td>
                    <td align="center"><?php echo $selisihWaktu; ?></td>
                    <td align="center"><input type="submit" name="hapus" value="HAPUS" style="font-size: 12px;"></td>
                    <td align="center"><input type="submit" name="update" value="UPDATE" style="font-size: 12px;"></td>
                </tr>
            </form>
            <?php
        }
    }
//Deepseek End
    if (isset($_POST['idrokok'])) {
        $ID = $_POST['idrokok'];
    }    
    if (isset($_POST['hariini'])) {
        $hariini = $_POST['hariini'];
    }
    $Hariini = new datetime($hariini);
    $Hariini = $Hariini->format('Y-m-d H:i:s');
    
    if (isset($_POST['hapus'])) {
        $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',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location = 'smoking.php?item=$item';
                    }
                });
            </script>";
        }        
    }
    if (isset($_POST['update'])) {
        $Update = mysqli_query($conn,"UPDATE novia_abc_user_counter SET tanggal='$Hariini' 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',
                    confirmButtonText: 'OK'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location = 'smoking.php?item=$item';
                    }
                });
            </script>";
        }        
    }
?>
</table>

<table width="100%" cellpadding="5">
        <tr class="satu">
            <td colspan="4"><button style="padding : 10px; width:100%; background-color:#B6B7C1;">Catatan Merokok 30 Hari Terakhir</button></td>
        </tr>
		<tr class="satu">
		    <th>Hari</th>
    		<th>Tanggal</th>
    		<th>Jumlah</th>
    		<th>Rupiah</th>
		</tr>
<?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'), // Interval 1 hari
    new DateTime($se . ' +1 day')
);

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

// Query data dari database
$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->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $tgl = $row['tanggal'];
        $tanggalArray[$tgl] = $row['total_rokok']; // Update nilai berdasarkan hasil query
    }
}
// Balik urutan array agar sesuai dengan DESC
$tanggalArray = array_reverse($tanggalArray);
// Tampilkan data dalam tabel
//$count = 0;
$bulan_aero = 0;
$sty = "satu";
$harga = 0;
$harga_bulan = 0;
$harga_total = 0;
foreach ($tanggalArray as $tgl => $total_rokok) {
    $bulan = new DateTime($tgl);
    $Hari = $bulan->format('l');
    $hari = $HARI[$Hari]; // Konversi nama hari (misalnya ke Bahasa Indonesia)
    $bulan_aero += $total_rokok;
    $harga = $total_rokok*$nilai;
    $harga_bulan = $bulan_aero*$nilai;
    //$count ++;
    //if ($count > 0) $sty = "satu";
    //if ($count > 7) $sty = "dua";
    
    //if ($bulan >= $tanggal_awal){
    if ($bulan->getTimestamp() >= $tanggal_awal->getTimestamp()) {
?>

    <tr class="dua">
        <td>
            <a href="#">
            <?php echo $hari; ?>
            </a>
        </td>
        <td align="center">
            <a href="#">
            <?php echo $tgl; ?>
            </a>
        </td>
        <td align="center"><?php echo $total_rokok; ?></td>
        <td align="center"><?php echo $harga; ?></td>
    </tr>
    <?php
    }
}
?>
    <tr class="satu">
        <td>TOTAL</td>
        <td align="center">30 Hari Terakhir</td>
        <td align="center"><?php echo $bulan_aero; ?></td>
        <td align="center"><?php echo $harga_bulan; ?></td>
    </tr>
    
    <tr class="satu">
            <td colspan="4"><button style="padding : 10px; width:100%; background-color:#B6B7C1;">Catatan MEROKOK per Bulan</button></td>
    </tr>    
	<tr class="satu">
		<th colspan="2" align="left">Tahun - Bulan</th>
		
		<th>Total Rokok (batang)</th>
		<th>Rupiah</th>
	</tr>
    <?php
    
    
    $tanggal_sekarang = new DateTime(date('Y-m-d'));
    $bulan_terakhir = date('Y-m');
    $bulan_array = [];

    // Hitung selisih bulan (tahun * 12 + bulan)
    $selisih_bulan = 
        (($tanggal_sekarang->format('Y') - $tanggal_awal->format('Y')) * 12)
        + ($tanggal_sekarang->format('m') - $tanggal_awal->format('m'));
    
    for ($i = 0; $i <= $selisih_bulan; $i++) {
        $bulan = date('Y-m', strtotime("-$i months", strtotime($bulan_terakhir)));
        $bulan_array[$bulan] = 0; // Default nilai 0
    }

    // Query untuk mengambil total aero per bulan
    $query = "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 = $conn->query($query);

    // Masukkan hasil query ke array bulan
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $bulan_array[$row['bulan']] = $row['total_rokok_bulan'];
        }
    }
    // Tampilkan semua bulan, termasuk yang totalnya 0
    foreach ($bulan_array as $bulan => $total) {
        $harga_total = $total*$nilai;
        ?>
        <tr class="dua">
            <td colspan="2"><?php echo $bulan; ?></td>
            <td align="center"><?php echo $total; ?></td>
            <td align="center"><?php echo $harga_total; ?></td>
        </tr>
        <?php
    }
    ?>
</table>

    <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
        }

        // Jalankan setiap 1 detik
        //setInterval(updateTimer, 1000);

        // Panggil pertama kali
        //updateTimer();
        
        if (<?php echo $selisih_detik; ?> < 300000000) {
            // Jalankan timer hanya jika ada data
            setInterval(updateTimer, 1000);
            updateTimer();
        } else {
            // Jika tidak ada data, tampilkan 00:00:00
            document.getElementById("timer").innerText = "00:00:00";
        }
        
    </script>

</body>
</html>