
<?php
session_start();
include 'koneksi.php';

// Cek koneksi database
if (!$conn) {
    die("Database tidak terhubung!");
}

// Cek login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['name'];

// Daftar kategori BARU - UNTUK PENGELUARAN
$kategori_list = [
    'CICILAN',
    'TRANSPORTASI', 
    'JAJAN',
    'BELANJA',
    'ROKOK',
    'KEBUTUHAN POKOK',
    'PEMBAYARAN',
    'LAINNYA'
  
    
];

// Daftar kategori PEMASUKAN
$kategori_pemasukan = [
    'GAJI',
    'BONUS', 
    'FREELANCE',
    'JUALAN',
    'HADIAH',
    'PINJAMAN',
    'LAINNYA'
];

// Simpan data - GUNAKAN 'keterangan' sesuai struktur database
if (isset($_POST['simpan'])) {
    $tanggal = mysqli_real_escape_string($conn, $_POST['tanggal']);
    $kategori = strtoupper(mysqli_real_escape_string($conn, $_POST['kategori']));
    $jenis = mysqli_real_escape_string($conn, $_POST['jenis']);
    $jumlah = mysqli_real_escape_string($conn, $_POST['jumlah']);
    $ket = mysqli_real_escape_string($conn, $_POST['ket']);
$keterangan = $kategori . " - " . $ket;
   $query = "INSERT INTO transaksi (user_id, tanggal, keterangan, jenis, jumlah) 
VALUES ('$user_id', '$tanggal', '$keterangan', '$jenis', '$jumlah')";
    if (mysqli_query($conn, $query)) {
        header("Location: index.php");
        exit;
    } else {
        echo "<script>alert('Gagal menyimpan: " . mysqli_error($conn) . "');</script>";
    }
}

// Ambil bulan dan tahun dari GET (default bulan ini)
$bulan_dipilih = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
$tahun_dipilih = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');

// Ambil data transaksi per kategori per bulan - GUNAKAN 'keterangan'
$kategori_query = mysqli_query($conn, "
    SELECT keterangan AS kategori,
           SUM(jumlah) AS total,
           COUNT(*) AS jumlah_transaksi
    FROM transaksi
    WHERE user_id='$user_id'
      AND jenis='pengeluaran' 
      AND MONTH(tanggal)='$bulan_dipilih'
      AND YEAR(tanggal)='$tahun_dipilih'
    GROUP BY keterangan
    ORDER BY total DESC
");

$kategori_data = [];
while($row = mysqli_fetch_assoc($kategori_query)){
    $kategori_data[] = $row;
}

// Ambil daftar bulan bahasa Indonesia
$bulan_indo = [
    '01'=>'Januari','02'=>'Februari','03'=>'Maret','04'=>'April','05'=>'Mei','06'=>'Juni',
    '07'=>'Juli','08'=>'Agustus','09'=>'September','10'=>'Oktober','11'=>'November','12'=>'Desember'
];

// Hitung total pemasukan & pengeluaran user
$total_query = mysqli_query($conn, "
    SELECT 
        SUM(CASE WHEN jenis='pemasukan' THEN jumlah ELSE 0 END) AS total_pemasukan,
        SUM(CASE WHEN jenis='pengeluaran' THEN jumlah ELSE 0 END) AS total_pengeluaran
    FROM transaksi
    WHERE user_id='$user_id'
");

$total_row = mysqli_fetch_assoc($total_query);
$total_pemasukan = $total_row['total_pemasukan'] ?? 0;
$total_pengeluaran = $total_row['total_pengeluaran'] ?? 0;
// DATA GRAFIK PEMASUKAN vs PENGELUARAN BULAN INI
$grafik_query = mysqli_query($conn,"
SELECT 
SUM(CASE WHEN jenis='pemasukan' THEN jumlah ELSE 0 END) AS pemasukan,
SUM(CASE WHEN jenis='pengeluaran' THEN jumlah ELSE 0 END) AS pengeluaran
FROM transaksi
WHERE user_id='$user_id'
AND MONTH(tanggal)='$bulan_dipilih'
AND YEAR(tanggal)='$tahun_dipilih'
");

$grafik_data = mysqli_fetch_assoc($grafik_query);

$grafik_pemasukan = $grafik_data['pemasukan'] ?? 0;
$grafik_pengeluaran = $grafik_data['pengeluaran'] ?? 0;
$total_saldo = $total_pemasukan - $total_pengeluaran;

// Hapus transaksi
if (isset($_GET['hapus'])) {
    $id = intval($_GET['hapus']);
    mysqli_query($conn, "DELETE FROM transaksi WHERE id='$id' AND user_id='$user_id'");
    header("Location: index.php");
    exit;
}

// Ambil recent data - GUNAKAN 'keterangan' 
$recent_query = mysqli_query($conn, "
    SELECT id, tanggal, keterangan AS kategori, jenis, jumlah
    FROM transaksi
    WHERE user_id='$user_id'
      AND MONTH(tanggal)='$bulan_dipilih'
      AND YEAR(tanggal)='$tahun_dipilih'
    ORDER BY tanggal DESC, id DESC
    LIMIT 10
");

$recent_data = [];
while($row = mysqli_fetch_assoc($recent_query)){
    $recent_data[] = $row;
}

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>silaku - Keuangan</title>
   <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        /* CSS sama persis seperti sebelumnya, hanya tambah CSS untuk 2 tombol float */
        *{
            margin:0;
            padding:0;
            box-sizing:border-box;
            -webkit-tap-highlight-color:transparent;
        }

          body{
    font-family:'Poppins',sans-serif;
    background:
    radial-gradient(circle at top left,#818cf8 0%,transparent 30%),
    radial-gradient(circle at bottom right,#c084fc 0%,transparent 30%),
    linear-gradient(135deg,#eef2ff,#f8fafc);
    height:100vh;
    overflow:hidden;
    display:flex;
    justify-content:center;
}

        .app{
    max-width:480px;
    width:100%;
    height:100vh;
    display:flex;
    flex-direction:column;
    background:rgba(255,255,255,.75);
    backdrop-filter:blur(20px);
    border:1px solid rgba(255,255,255,.3);
    border-radius:30px;
    overflow-y:auto;
    box-shadow:0 20px 60px rgba(0,0,0,.15);
    position:relative;
}

        /* HEADER */
        .header{
    background:
    linear-gradient(135deg,#4f46e5,#7c3aed,#9333ea);
    color:white;
    padding:35px 20px 50px;
    border-bottom-left-radius:35px;
    border-bottom-right-radius:35px;
    flex-shrink:0;
    position:relative;
    overflow:hidden;
}

        .header-top{
            display:flex;
            justify-content:space-between;
            align-items:center;
        }

        .user-info h1{
            font-size:20px;
            font-weight:700;
        }

        .user-info p{
            font-size:13px;
            opacity:.8;
        }

        .logout-btn{
            background:rgba(255,255,255,0.2);
            padding:8px 15px;
            border-radius:20px;
            text-decoration:none;
            color:white;
            font-size:12px;
        }

        /* SALDO */
        .saldo-card{
    background:
    linear-gradient(135deg,#06b6d4,#3b82f6,#6366f1);
    margin:-35px 20px 20px;
    padding:30px;
    border-radius:30px;
    color:white;
    box-shadow:0 20px 50px rgba(59,130,246,.35);
    flex-shrink:0;
    position:relative;
    overflow:hidden;
}

        .saldo-label{
            font-size:13px;
            opacity:.9;
        }

        .saldo-amount{
            font-size:38px;
            font-weight:800;
            margin:10px 0 20px;
        }

        .saldo-stats{
            display:flex;
            justify-content:space-between;
        }

        .stat{
            text-align:center;
        }

        .stat-label{
            font-size:11px;
            opacity:.8;
        }

        .stat-value{
            font-weight:700;
            font-size:14px;
        }

        /* CONTENT */
        .content{
            flex:1;
            overflow-y: auto;
            padding:20px;
            padding-bottom: 120px; /* Diperbesar untuk 2 tombol */
        }

        .section-title{
            font-weight:700;
            margin-bottom:15px;
            display:flex;
            justify-content:space-between;
        }

        /* TRANSAKSI */
        .transaksi-list{
            display:flex;
            flex-direction:column;
            gap:10px;
        }

        .transaksi-item{
    display:flex;
    align-items:center;
    padding:15px;
    background:rgba(255,255,255,.85);
    backdrop-filter:blur(12px);
    border-radius:22px;
    border:1px solid rgba(255,255,255,.4);
    box-shadow:0 10px 25px rgba(0,0,0,0.05);
    transition:.3s;
    animation:fadeIn .4s ease;
}

        .transaksi-item:hover{
            transform:translateY(-3px);
            box-shadow:0 10px 20px rgba(0,0,0,0.1);
        }

        @keyframes fadeIn{
            from{opacity:0;transform:translateY(10px);}
            to{opacity:1;transform:translateY(0);}
        }

        .transaksi-info{
            flex:1;
        }

        .transaksi-title{
            font-size:14px;
            font-weight:600;
            text-transform: uppercase;
        }

        .transaksi-date{
            font-size:11px;
            color:#888;
        }

        .transaksi-amount{
            font-weight:700;
            font-size:14px;
        }

        .amount-income{color:#16a34a;}
        .amount-expense{color:#dc2626;}

 
        .btn-income {
            background:linear-gradient(135deg,#16a34a,#22c55e);
        }
.btn-float:hover::before{
    animation:shine .8s ease;
}

@keyframes shine{
    100%{
        left:130%;
    }
}
.btn-float:hover{
    transform:
    translateY(-5px)
    scale(1.06);

    box-shadow:
    0 18px 35px rgba(0,0,0,.25),
    0 0 20px rgba(255,255,255,.15);
}.btn-float:active{
    transform:scale(.94);
}
     .btn-income{
    background:
    linear-gradient(
        135deg,
        #22c55e,
        #16a34a,
        #15803d
    );
}


      .btn-expense{
    background:
    linear-gradient(
        135deg,
        #ef4444,
        #dc2626,
        #991b1b
    );
}
.btn-scan{
    background:
    linear-gradient(
        135deg,
        #38bdf8,
        #2563eb,
        #4f46e5
    );
}

/* EFEK GLOW */
.btn-income:hover{
    box-shadow:
    0 18px 35px rgba(34,197,94,.45);
}

.btn-expense:hover{
    box-shadow:
    0 18px 35px rgba(239,68,68,.45);
}

.btn-scan:hover{
    box-shadow:
    0 18px 35px rgba(59,130,246,.45);
}
        .btn-expense:hover {
            transform:scale(1.1);
        }

        /* MODAL */
        .modal{
            display:none;
            position:fixed;
            top:0;
            left:0;
            width:100%;
            height:100%;
            background:rgba(0,0,0,0.6);
            align-items:center;
            justify-content:center;
            z-index:200;
            padding:20px;
            overflow-y:auto;
        }

        .modal.active{display:flex;}

        .modal-content{
            background:white;
            padding:25px;
            border-radius:20px;
            width:100%;
            max-width:380px;
            max-height:90vh;
            overflow-y:auto;
            animation:slideUp .3s ease;
        }

        @keyframes slideUp{
            from{transform:translateY(50px);opacity:0;}
            to{transform:translateY(0);opacity:1;}
        }

        .form-group{
            margin-bottom:15px;
        }

        .form-group label{
            font-size:12px;
            color:#555;
            font-weight:600;
            display:block;
            margin-bottom:5px;
        }

        .form-group input,
        .form-group select{
            width:100%;
            padding:12px;
            border-radius:10px;
            border:1px solid #ddd;
            font-size:14px;
        }

        .btn-submit{
            width:100%;
            padding:14px;
            border:none;
            border-radius:10px;
            background:linear-gradient(135deg,#4f46e5,#9333ea);
            color:white;
            font-weight:700;
            cursor:pointer;
            margin-top:10px;
        }

        /* NAVBAR */
        .bottom-nav{
            display:flex;
            justify-content:space-around;
            padding:12px;
            border-top:1px solid #eee;
            background:white;
            position: fixed;
            bottom: 0;
            width: 100%;
            max-width: 480px;
            z-index: 90;
        }

        .nav-item{
            text-align:center;
            font-size:11px;
            color:#888;
            text-decoration:none;
        }

        .nav-item.active{color:#4f46e5;}

        .nav-icon{
            font-size:20px;
            display:block;
        }

        @media (max-width:480px){
            .float-buttons{right:20px;}
        }

        .transaksi-item:active{transform:scale(0.97);background:#f1f5f9;}
         
        .transaksi-delete-btn {
            margin-left: 10px;
            color: white;
            background: red;
            border-radius: 8px;
            padding: 6px 10px;
            font-size: 14px;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: transform 0.2s;
            text-transform: uppercase;
            font-weight: 600;
        }

        .transaksi-delete-btn:hover {
            transform: scale(1.1);
            background: darkred;
        }

        .no-data {
            text-align:center;
            font-size:14px;
            color:#888;
            padding:40px 20px;
            background:#f8fafc;
            border-radius:18px;
            margin-top:20px;
        }
        /* =========================
/* =========================
   HAMBURGER FLOAT MENU
========================= */

.fab-container{
    position:fixed;
    top:15px;
    right:15px;
    z-index:999;

    display:flex;
    flex-direction:column;
    align-items:flex-end;
}

/* SEARCH INPUT */
.fab-search{
    margin-top:10px;
    width:220px;

    background:rgba(255,255,255,.95);
    backdrop-filter:blur(10px);

    border:none;
    outline:none;

    padding:12px 16px;

    border-radius:16px;

    font-size:13px;
    font-family:'Poppins',sans-serif;

    box-shadow:
    0 8px 20px rgba(0,0,0,.08);

    transition:.3s;
}

.fab-search:focus{
    transform:scale(1.02);
    box-shadow:
    0 10px 25px rgba(79,70,229,.2);
}

/* MAIN BUTTON */
.fab-main{
    width:62px;
    height:62px;

    border:none;
    border-radius:20px;

    background:
    linear-gradient(
        135deg,
        rgb(179, 187, 179),
        rgb(179, 187, 179),
       rgb(179, 187, 179)
    );

    color:white;
    font-size:28px;
    cursor:pointer;

    box-shadow:
    0 10px 25px rgba(0,0,0,.2);

    transition:.3s;
}

.fab-main:hover{
    transform:scale(1.08);
}

/* MENU KE BAWAH */
.fab-menu{
    position:absolute;
    top:0;
    right:75px;

    display:flex;
    flex-direction:row; /* horizontal */
    gap:12px;

    opacity:0;
    visibility:hidden;

    transform:translateX(20px);

    transition:.3s;
}

/* ACTIVE */
.fab-menu.active{
    opacity:1;
    visibility:visible;

    transform:translateX(0);
}
/* ITEM */
.fab-item{
    width:58px;
    height:58px;

    border:none;
    border-radius:18px;

    color:white;
    font-size:24px;
    font-weight:700;

    cursor:pointer;

    box-shadow:
    0 8px 20px rgba(0,0,0,.18);

    transition:.25s;
}

.fab-item:hover{
    transform:scale(1.08);
}

/* WARNA */
.btn-income{
    background:
    linear-gradient(
        135deg,
        #22c55e,
        #16a34a
    );
}

.btn-expense{
    background:
    linear-gradient(
        135deg,
        #ef4444,
        #dc2626
    );
}

.btn-scan{
    background:
    linear-gradient(
        135deg,
        #38bdf8,
        #2563eb
    );
}
.fab-main{
    width:62px;
    height:62px;

    border:none;
    border-radius:20px;

    background:
    linear-gradient(
        135deg,
        rgb(179, 187, 179),
        rgb(179, 187, 179),
        rgb(179, 187, 179)
    );

    color:white;
    font-size:14px; /* ubah */
    font-weight:700; /* tambah */
    cursor:pointer;

    box-shadow:
    0 10px 25px rgba(0,0,0,.2);

    transition:.3s;
}
.btn-voice{
    background:
    linear-gradient(
        135deg,
        #ec4899,
        #be185d
    );
}

.btn-voice:hover{
    box-shadow:
    0 18px 35px rgba(236,72,153,.45);
}
    </style>
</head>
<body>

<div class="app">
    <!-- Header -->
    <div class="header">
        <div class="header-top">
            <div class="user-info">
                <h1>Halo, <?php echo htmlspecialchars($user_name); ?></h1>
                <p>Selamat datang kembali di <b><i>SILAKU</i></b></p>
                <p>created by faizz</p>
            </div>
          
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        </div>
    </div>

    <!-- Saldo Card -->
    <div class="saldo-card">
        <div class="saldo-label">Total Saldo Anda</div>
        <div class="saldo-amount">Rp <?php echo number_format($total_saldo, 0, ',', '.'); ?></div>

    </div>

    <!-- Content -->
    <div class="content">
    <div class="section-title">

<span>Transaksi Terbaru</span>

<form method="GET" style="display:flex; align-items:center; gap:6px;">

<select name="bulan" onchange="this.form.submit()" 
style="
padding:4px 8px;
border-radius:8px;
border:1px solid #ddd;
font-size:12px;
background:#f8fafc;
cursor:pointer;
">

<?php
foreach($bulan_indo as $num => $nama){
    $selected = ($num == $bulan_dipilih) ? "selected" : "";
    echo "<option value='$num' $selected>$nama</option>";
}
?>

</select>

<select name="tahun" onchange="this.form.submit()" 
style="
padding:4px 8px;
border-radius:8px;
border:1px solid #ddd;
font-size:12px;
background:#f8fafc;
cursor:pointer;
">

<?php
for($i=date('Y'); $i>=2020; $i--){
    $selected = ($i == $tahun_dipilih) ? "selected" : "";
    echo "<option value='$i' $selected>$i</option>";
}
?>

</select>

</form>

</div>
        
        <div class="transaksi-list">
            <div style="background:white; padding:20px; border-radius:18px; margin-bottom:20px; box-shadow:0 5px 15px rgba(0,0,0,0.05);">

<h3 style="margin-bottom:10px;">📊 Grafik Keuangan</h3>

<canvas id="grafikKeuangan" height="120"></canvas>
<div style="margin-top:20px;">
    <canvas id="pieChart" height="180"></canvas>
</div>
<div style="margin-top:10px; font-size:12px; color:#555;">

<div style="display:flex; justify-content:space-between;">
<span>🟢 Pemasukan</span>
<span style="font-weight:600;">
Rp <?php echo number_format($grafik_pemasukan,0,',','.'); ?>
</span>
</div>

<div style="display:flex; justify-content:space-between; margin-top:4px;">
<span>🔴 Pengeluaran</span>
<span style="font-weight:600;">
Rp <?php echo number_format($grafik_pengeluaran,0,',','.'); ?>
</span>
</div>

</div>

</div>
        <?php
        if(count($recent_data) > 0){
            foreach($recent_data as $item){
                $amount_class = ($item['jenis']=='pemasukan')?'amount-income':'amount-expense';
                echo '<div class="transaksi-item">';
                echo '<div class="transaksi-info">';
                echo '<div class="transaksi-title">'.$item['kategori'].'</div>';
                echo '<div class="transaksi-date">'.date('d-m-Y H:i', strtotime($item['tanggal'])).'</div>';
                echo '<div class="transaksi-amount '.$amount_class.'">Rp '.number_format($item['jumlah'],0,',','.').'</div>';
                echo '</div>';
                echo '<a href="index.php?hapus='.$item['id'].'" class="transaksi-delete-btn" onclick="return confirm(\'Hapus transaksi '.$item['kategori'].'?\')">🗑</a>';
                echo '</div>';
            }
        }else{
            echo '<div class="no-data">';
            echo 'Belum ada transaksi<br>';
            echo '<small style="opacity:0.7;">Klik tombol + atau - untuk menambah transaksi pertama</small>';
            echo '</div>';
        }
    
        ?>
        </div>
    </div>

<!-- HAMBURGER FLOAT MENU -->
<div class="fab-container">

    <!-- MENU ITEM -->
    <div class="fab-menu" id="fabMenu">
       <button class="fab-item btn-voice" onclick="openVoice()">
    🎤
</button>
        <button class="fab-item btn-scan" onclick="openScan()">
            📷
        </button>

        <button class="fab-item btn-income" onclick="openModal('pemasukan')">
            +
        </button>

        <button class="fab-item btn-expense" onclick="openModal('pengeluaran')">
            -
        </button>

    </div>

    <!-- MAIN BUTTON -->
<!-- MAIN BUTTON -->
<button class="fab-main" onclick="toggleFab()">
    Input Disini
</button>
    <!-- Bottom Nav -->
    <div class="bottom-nav">
        <a href="index.php" class="nav-item active">
            <span class="nav-icon">🏠</span>
            Beranda
        </a>
        <a href="laporan.php" class="nav-item">
            <span class="nav-icon">📊</span>
            Laporan
        </a>
        <a href="profil.php" class="nav-item">
            <span class="nav-icon">👤</span>
            Profil
        </a>
    </div>

   <!-- Modal Form PEMASUKAN -->
<div class="modal" id="modal-pemasukan">
    <div class="modal-content">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h3>Tambah Pemasukan</h3>
            <button onclick="closeModal('pemasukan')" style="border:none; background:none; font-size:24px; cursor:pointer;">&times;</button>
        </div>
        <form method="POST" action="">
            <div class="form-group">
                <label>Tanggal *</label>
                <input type="date" name="tanggal" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
            <div class="form-group">
                <label>Kategori Pemasukan *</label>
                <select name="kategori" required style="text-transform: uppercase; font-weight: 600;">
                    <option value="">Pilih Kategori</option>
                    <?php foreach($kategori_pemasukan as $kategori): ?>
                    <option value="<?php echo $kategori; ?>"><?php echo $kategori; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Jumlah (Rp) *</label>
              <input 
type="text"
name="jumlah"
placeholder="50000"
inputmode="numeric"
required>
            </div>
            <div class="form-group">
    <label>Keterangan</label>
    <input type="text" name="ket" placeholder="">
    </div>
            <input type="hidden" name="jenis" value="pemasukan">
            <button type="submit" name="simpan" class="btn-submit">💰 Simpan Pemasukan</button>
        </form>
    </div>
</div>

<!-- Modal Form PENGELUARAN -->
<div class="modal" id="modal-pengeluaran">
    <div class="modal-content">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h3>Tambah Pengeluaran</h3>
            <button onclick="closeModal('pengeluaran')" style="border:none; background:none; font-size:24px; cursor:pointer;">&times;</button>
        </div>
        <form method="POST" action="">
            <div class="form-group">
                <label>Tanggal *</label>
                <input type="date" name="tanggal" value="<?php echo date('Y-m-d'); ?>" required>
            </div>
            <div class="form-group">
                <label>Kategori Pengeluaran *</label>
                <select name="kategori" required style="text-transform: uppercase; font-weight: 600;">
                    <option value="">Pilih Kategori</option>
                    <?php foreach($kategori_list as $kategori): ?>
                    <option value="<?php echo $kategori; ?>"><?php echo $kategori; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Jumlah (Rp) *</label>
               <input 
type="text"
name="jumlah"
placeholder="50000"
inputmode="numeric"
required>
            </div>
            <div class="form-group">
<label>Keterangan</label>
<input type="text" name="ket" placeholder="Contoh: Jika  CICILAN: Motor">
</div>
            <input type="hidden" name="jenis" value="pengeluaran">
            <button type="submit" name="simpan" class="btn-submit">💸 Simpan Pengeluaran</button>
        </form>
    </div>
</div>
<div class="modal" id="modal-scan">
    <div class="modal-content">

        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;">
            <h3>📷 AI Scan Struk</h3>

            <div style="
            background:linear-gradient(135deg,#0ea5e9,#6366f1);
            color:white;
            padding:6px 12px;
            border-radius:999px;
            font-size:11px;
            font-weight:700;
            ">
                AI OCR
            </div>
        </div>

       <div style="display:flex; flex-direction:column; gap:10px;">

    <!-- Tombol Kamera -->
    <button type="button"
    onclick="openCamera()"
    style="
    width:100%;
    padding:14px;
    border:none;
    border-radius:14px;
    background:linear-gradient(135deg,#0ea5e9,#2563eb);
    color:white;
    font-weight:700;
    font-size:14px;
    cursor:pointer;
    ">
        📷 Ambil dari Kamera
    </button>

    <!-- Tombol Galeri -->
    <button type="button"
    onclick="openGallery()"
    style="
    width:100%;
    padding:14px;
    border:none;
    border-radius:14px;
    background:linear-gradient(135deg,#8b5cf6,#6366f1);
    color:white;
    font-weight:700;
    font-size:14px;
    cursor:pointer;
    ">
        🖼 Pilih dari Galeri
    </button>

    <!-- Input Kamera -->
    <input 
    type="file"
    id="cameraInput"
    accept="image/*"
    capture="environment"
    style="display:none;">

    <!-- Input Galeri -->
    <input 
    type="file"
    id="galleryInput"
    accept="image/*"
    style="display:none;">

</div>

    <div style="display:flex; gap:10px; margin-top:15px;">

    <button onclick="closeScan()" 
    type="button"
    style="
    flex:1;
    padding:14px;
    border:none;
    border-radius:14px;
    background:#e5e7eb;
    color:#111827;
    font-weight:700;
    cursor:pointer;
    ">
        ❌ Batal
    </button>

    <button onclick="scanStruk()" 
    type="button"
    class="btn-submit"
    style="flex:1; margin-top:0;">
        📸 Scan
    </button>

</div>

        <div id="hasilScan" style="
        margin-top:15px;
        background:#f8fafc;
        padding:15px;
        border-radius:15px;
        font-size:12px;
        max-height:250px;
        overflow:auto;
        "></div>

    </div>
</div>
<!-- MODAL VOICE AI -->
<div class="modal" id="modal-voice">

    <div class="modal-content">

        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
            <h3>🎤 AI Voice Input</h3>

            <button onclick="closeVoice()"
            style="
            border:none;
            background:none;
            font-size:24px;
            cursor:pointer;
            ">
                &times;
            </button>
        </div>

        <div id="voiceStatus"
        style="
        text-align:center;
        padding:20px;
        background:#f8fafc;
        border-radius:15px;
        margin-bottom:15px;
        font-size:14px;
        ">
            Tekan tombol mulai bicara
        </div>

        <button onclick="startVoiceAI()"
        style="
        width:100%;
        padding:16px;
        border:none;
        border-radius:16px;
        background:linear-gradient(135deg,#ec4899,#be185d);
        color:white;
        font-size:16px;
        font-weight:700;
        cursor:pointer;
        ">
            🎙 Mulai Rekam
        </button>

    </div>

</div>
<script>
function openModal(jenis) {
    if (jenis === 'pemasukan') {
        document.getElementById('modal-pemasukan').classList.add('active');
    } else {
        document.getElementById('modal-pengeluaran').classList.add('active');
    }
}

function closeModal(jenis) {
    if (jenis === 'pemasukan') {
        document.getElementById('modal-pemasukan').classList.remove('active');
    } else {
        document.getElementById('modal-pengeluaran').classList.remove('active');
    }
}

// Tutup modal jika klik di luar
document.getElementById('modal-pemasukan').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal('pemasukan');
    }
});

document.getElementById('modal-pengeluaran').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal('pengeluaran');
    }
});
const ctx = document.getElementById('grafikKeuangan');

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Pemasukan','Pengeluaran'],
        datasets: [{
            data: [
                <?php echo $grafik_pemasukan; ?>,
                <?php echo $grafik_pengeluaran; ?>
            ],
            backgroundColor: [
                '#22c55e',
                '#ef4444'
            ],
            borderRadius:8
        }]
    },
    options:{
        plugins:{
            legend:{
                display:false
            }
        },
        scales:{
            y:{
                beginAtZero:true
            }
        }
    }
});
</script>

<script src="https://unpkg.com/tesseract.js@4.1.1/dist/tesseract.min.js"></script>

<script>
navigator.mediaDevices.getUserMedia({ audio:true })
.then(function(stream){
    console.log("Mic diizinkan");
})
.catch(function(err){
    alert("Mic ditolak: " + err);
});

function openScan(){
    document.getElementById('modal-scan').classList.add('active');
}
let selectedFile = null;
function closeScan(){

    document.getElementById('modal-scan')
    .classList.remove('active');

    selectedFile = null;

    document.getElementById('hasilScan').innerHTML = '';

    document.getElementById('cameraInput').value = '';
    document.getElementById('galleryInput').value = '';
}
document.getElementById('modal-scan')
.addEventListener('click', function(e){

    if(e.target === this){
        closeScan();
    }

});
function openCamera(){
    document.getElementById('cameraInput').click();
}

function openGallery(){
    document.getElementById('galleryInput').click();
}

document.getElementById('cameraInput')
.addEventListener('change', function(e){

    selectedFile = e.target.files[0];

    if(selectedFile){
        scanStruk();
    }
});

document.getElementById('galleryInput')
.addEventListener('change', function(e){

    selectedFile = e.target.files[0];

    if(selectedFile){
        scanStruk();
    }
});
async function scanStruk(){

   const file = selectedFile;

    if(!file){
        alert("Pilih gambar dulu!");
        return;
    }

    const hasil = document.getElementById('hasilScan');

    hasil.innerHTML = "⏳ AI sedang membaca struk...";

    const { data:{ text } } = await Tesseract.recognize(
        file,
        'eng',
        {
            logger:m=>console.log(m)
        }
    );

    console.log(text);

    // =========================
    // NORMALISASI OCR
    // =========================

    let cleanText = text
    .replace(/O/g,'0')
    .replace(/D/g,'0')
    .replace(/B/g,'8')
    .replace(/l/g,'1')
    .replace(/\|/g,'1')
    .replace(/,/g,'.')
    .replace(/Rp/gi,'')
    .replace(/rp/gi,'');

    // Pisah per baris
    let lines = cleanText
    .split('\n')
    .map(x => x.trim())
    .filter(x => x.length > 0);

    // =========================
    // DETEKSI TOKO
    // =========================

    let toko = "Belanja";

    if(/indomaret/i.test(cleanText)){
        toko = "Indomaret";
    }
    else if(/alfamart/i.test(cleanText)){
        toko = "Alfamart";
    }
    else if(/superindo/i.test(cleanText)){
        toko = "Superindo";
    }
    else if(/mixue/i.test(cleanText)){
        toko = "Mixue";
    }
    else if(/pertamina/i.test(cleanText)){
        toko = "Pertamina";
    }
    else if(/mcd|mcdonald/i.test(cleanText)){
        toko = "McDonalds";
    }
    else if(/kfc/i.test(cleanText)){
        toko = "KFC";
    }

    // =========================
    // DETEKSI KATEGORI
    // =========================

    let kategori = "LAINNYA";

    if(/indomaret|alfamart|superindo/i.test(cleanText)){
        kategori = "KEBUTUHAN POKOK";
    }
    else if(/pertamina|shell/i.test(cleanText)){
        kategori = "TRANSPORTASI";
    }
    else if(/mixue|kopi|mcd|kfc|cafe|resto/i.test(cleanText)){
        kategori = "JAJAN";
    }

    // =========================
    // CARI TOTAL AKURAT
    // =========================

    let total = 0;

    const priorityKeywords = [
        'grand total',
        'total bayar',
        'jumlah bayar',
        'total belanja',
        'total',
        'cash',
        'tunai'
    ];

    for(let line of lines){

        let lower = line.toLowerCase();

        // LEWATI BARIS TANGGAL/JAM
        if(
            /\d{2}\/\d{2}\/\d{4}/.test(line) ||
            /\d{2}:\d{2}/.test(line)
        ){
            continue;
        }

        for(let key of priorityKeywords){

            if(lower.includes(key)){

                // Ambil semua angka di baris
                let numbers = line.match(/\d[\d\.]+/g);

                if(numbers){

                    for(let num of numbers){

                        let value = parseInt(
                            num.replace(/\./g,'')
                        );

                        // filter nominal wajar
                        if(
                            value > 1000 &&
                            value < 10000000
                        ){
                            total = value;
                        }
                    }
                }
            }
        }
    }

    // =========================
    // FALLBACK CERDAS
    // =========================

    if(total <= 0){

        let semuaAngka = cleanText.match(/\d[\d\.]+/g);

        if(semuaAngka){

            let kandidat = semuaAngka
            .map(x => parseInt(
                x.replace(/\./g,'')
            ))

            .filter(x =>

                x > 1000 &&
                x < 10000000 &&

                // hindari tahun
                x !== 2024 &&
                x !== 2025 &&
                x !== 2026
            );

            if(kandidat.length > 0){

                // ambil angka terbesar kedua
                kandidat.sort((a,b)=>b-a);

                total = kandidat[0];
            }
        }
    }

    // =========================
    // VALIDASI
    // =========================

    if(total <= 0){

        hasil.innerHTML =
        "❌ Total gagal dibaca";

        alert("Total tidak ditemukan");
        return;
    }

    // =========================
    // TUTUP MODAL
    // =========================

    document.getElementById('modal-scan')
    .classList.remove('active');

    // =========================
    // AUTO FORM
    // =========================

    openModal('pengeluaran');

    setTimeout(()=>{

        document.querySelector(
            '#modal-pengeluaran input[name="tanggal"]'
        ).value =
        new Date().toISOString().split('T')[0];

        document.querySelector(
            '#modal-pengeluaran input[name="jumlah"]'
        ).value = total;

        document.querySelector(
            '#modal-pengeluaran select[name="kategori"]'
        ).value = kategori;

        document.querySelector(
            '#modal-pengeluaran input[name="ket"]'
        ).value = toko;

    },200);

    // =========================
    // HASIL
    // =========================

    hasil.innerHTML = `
        <div style="line-height:1.8">
            <b>🏪 ${toko}</b><br>
            📂 ${kategori}<br>
            💰 <b>Rp ${total.toLocaleString('id-ID')}</b>
        </div>
    `;

    alert(
        "✅ Scan berhasil\n\n" +
        "🏪 " + toko + "\n" +
        "📂 " + kategori + "\n" +
        "💰 Rp " + total.toLocaleString('id-ID')
    );
}
const pie = document.getElementById('pieChart');

new Chart(pie, {
    type:'doughnut',
    data:{
        labels:[
            <?php
            foreach($kategori_data as $item){
                echo "'" . $item['kategori'] . "',";
            }
            ?>
        ],

        datasets:[{
            data:[
                <?php
                foreach($kategori_data as $item){
                    echo $item['total'] . ",";
                }
                ?>
            ],

            backgroundColor:[
                '#ef4444',
                '#f97316',
                '#eab308',
                '#22c55e',
                '#06b6d4',
                '#3b82f6',
                '#8b5cf6',
                '#ec4899',
                '#14b8a6',
                '#84cc16'
            ],

            borderWidth:0
        }]
    },

    options:{
        cutout:'65%',

        plugins:{
            legend:{
                position:'bottom',
                labels:{
                    padding:15,
                    font:{
                        size:11
                    }
                }
            },

            tooltip:{
                callbacks:{
                    label:function(context){

                        let value = context.raw;

                        return ' Rp ' + value.toLocaleString('id-ID');
                    }
                }
            }
        }
    }
});
function toggleFab(){

    document
    .getElementById('fabMenu')
    .classList
    .toggle('active');

}
function openVoice(){
    document
    .getElementById('modal-voice')
    .classList.add('active');
}

function closeVoice(){
    document
    .getElementById('modal-voice')
    .classList.remove('active');
}

function startVoiceAI(){

    const SpeechRecognition =
        window.SpeechRecognition ||
        window.webkitSpeechRecognition;

    if(!SpeechRecognition){
        alert("Browser tidak support Voice AI");
        return;
    }

    const recognition = new SpeechRecognition();

    recognition.lang = 'id-ID';
    recognition.continuous = false;
    recognition.interimResults = false;

    recognition.start();

    document.getElementById('voiceStatus').innerHTML =
    "🎤 Mendengarkan...";

    recognition.onresult = function(event){

        let text =
        event.results[0][0].transcript;

        document.getElementById('voiceStatus').innerHTML =
        "✅ " + text;

        prosesVoiceAI(text);
    };

    recognition.onerror = function(event){

        console.log(event);

        alert(
            "Voice Error: " +
            event.error
        );
    };
}
function prosesVoiceAI(text){

    let lower = text.toLowerCase();

    let jenis = "pengeluaran";

    // =====================
    // DETEKSI JENIS
    // =====================

    if(
        lower.includes('gaji') ||
        lower.includes('bonus') ||
        lower.includes('pemasukan') ||
        lower.includes('dibayar')
    ){
        jenis = "pemasukan";
    }

    // =====================
    // DETEKSI KATEGORI
    // =====================

    let kategori = "LAINNYA";

    if(lower.includes('rokok')){
        kategori = "ROKOK";
    }
    else if(
        lower.includes('makan') ||
        lower.includes('bakso') ||
        lower.includes('kopi') ||
        lower.includes('jajan')
    ){
        kategori = "JAJAN";
    }
    else if(
        lower.includes('bensin') ||
        lower.includes('pertalite') ||
        lower.includes('transport')
    ){
        kategori = "TRANSPORTASI";
    }
    else if(
        lower.includes('belanja')
    ){
        kategori = "BELANJA";
    }

    // =====================
    // AMBIL ANGKA
    // =====================

    let jumlah = 0;

    let angka = lower.match(/\d+/g);

    if(angka){

        jumlah =
        parseInt(angka.join(''));
    }

    // =====================
    // VALIDASI
    // =====================

    if(jumlah <= 0){

        alert(
            "Nominal tidak ditemukan.\n\nContoh:\nJajan 15000 bakso"
        );

        return;
    }

    // =====================
    // AUTO OPEN FORM
    // =====================

    closeVoice();

    openModal(jenis);

    setTimeout(()=>{

        const modal =
        document.getElementById(
            'modal-' + jenis
        );

        modal.querySelector(
            'input[name="jumlah"]'
        ).value = jumlah;

        modal.querySelector(
            'select[name="kategori"]'
        ).value = kategori;

        modal.querySelector(
            'input[name="ket"]'
        ).value = text;

    },300);

    alert(
        "✅ Voice AI berhasil\n\n" +
        "Kategori: " + kategori + "\n" +
        "Jumlah: Rp " +
        jumlah.toLocaleString('id-ID')
    );
}


function startVoiceInput(){

    const SpeechRecognition =
        window.SpeechRecognition ||
        window.webkitSpeechRecognition;

    if(!SpeechRecognition){
        alert("Browser tidak support voice");
        return;
    }

    const recognition = new SpeechRecognition();

    recognition.lang = 'id-ID';
    recognition.start();

    alert("🎤 Silakan bicara...");

    recognition.onresult = function(event){

        let text =
        event.results[0][0].transcript
        .toLowerCase();

        console.log(text);

        // =====================
        // DETEKSI KATEGORI
        // =====================

        let kategori = "LAINNYA";

        if(text.includes('jajan')){
            kategori = "JAJAN";
        }
        else if(text.includes('rokok')){
            kategori = "ROKOK";
        }
        else if(text.includes('transport')){
            kategori = "TRANSPORTASI";
        }
        else if(text.includes('belanja')){
            kategori = "BELANJA";
        }

        // =====================
        // DETEKSI NOMINAL
        // =====================

        let jumlah = 0;

        // contoh:
        // "20 ribu"
        // "15 ribu"
        // "2 juta"

        let ribuMatch =
        text.match(/(\d+)\s*ribu/);

        let jutaMatch =
        text.match(/(\d+)\s*juta/);

        if(ribuMatch){
            jumlah =
            parseInt(ribuMatch[1]) * 1000;
        }
        else if(jutaMatch){
            jumlah =
            parseInt(jutaMatch[1]) * 1000000;
        }
        else{

            let angka =
            text.match(/\d+/);

            if(angka){
                jumlah =
                parseInt(angka[0]);
            }
        }

        if(jumlah <= 0){
            alert("Jumlah tidak terbaca");
            return;
        }

        // =====================
        // AUTO FORM
        // =====================

        openModal('pengeluaran');

        setTimeout(()=>{

            document.querySelector(
            '#modal-pengeluaran select[name="kategori"]'
            ).value = kategori;

            document.querySelector(
            '#modal-pengeluaran input[name="jumlah"]'
            ).value = jumlah;

            document.querySelector(
            '#modal-pengeluaran input[name="ket"]'
            ).value = text;

        },200);

        alert(
            "✅ Voice berhasil\n\n" +
            "Kategori: " + kategori + "\n" +
            "Jumlah: Rp " +
            jumlah.toLocaleString('id-ID')
        );
    };
}


</script>
</body>
</html>
