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

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

$user_id = $_SESSION['user_id'];

// 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: laporan.php");
    exit;
}

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

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

// Ambil bulan yang dipilih (default: bulan ini)
$bulan_dipilih = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
$tahun_dipilih = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');
$tanggal_dipilih = isset($_GET['tanggal']) ? $_GET['tanggal'] : '';

// Ambil Data Pertanggal
if($tanggal_dipilih != ''){
    $query = mysqli_query($conn, "SELECT * FROM transaksi
    WHERE user_id='$user_id'
    AND jenis='pengeluaran'
    AND DATE(tanggal)='$tanggal_dipilih'
    ORDER BY tanggal DESC");
}else{
    $query = mysqli_query($conn, "SELECT * FROM transaksi
    WHERE user_id='$user_id'
    AND jenis='pengeluaran'
    AND MONTH(tanggal)='$bulan_dipilih'
    AND YEAR(tanggal)='$tahun_dipilih'
    ORDER BY tanggal DESC");
}

// Debugging: Cek jumlah data
$data_count = mysqli_num_rows($query);

// Hitung total pengeluaran
$total_pengeluaran = 0;
while ($row = mysqli_fetch_assoc($query)) {
    $total_pengeluaran += $row['jumlah'];
}

// Statistik pengeluaran berdasarkan kategori (SEMUA kategori)
$statistik_query = mysqli_query($conn, "
    SELECT keterangan, 
           SUM(jumlah) as total_kategori,
           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_kategori DESC
");

$kategori_rank = [];
while($row = mysqli_fetch_assoc($statistik_query)){
    $kategori_rank[] = $row;
}

// Hitung jumlah hari yang ada transaksi
$hari_query = mysqli_query($conn, "
SELECT COUNT(DISTINCT tanggal) as jumlah_hari
FROM transaksi
WHERE user_id='$user_id'
AND jenis='pengeluaran'
AND MONTH(tanggal)='$bulan_dipilih'
AND YEAR(tanggal)='$tahun_dipilih'
");

$hari_data = mysqli_fetch_assoc($hari_query);
$jumlah_hari = $hari_data['jumlah_hari'];

// Hitung rata-rata per hari
$rata_harian = ($jumlah_hari > 0) ? $total_pengeluaran / $jumlah_hari : 0;

?>

<!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>Laporan - Silaku</title>
    <style>
    *{
        margin:0;
        padding:0;
        box-sizing:border-box;
        -webkit-tap-highlight-color:transparent;
    }

    html {
        scroll-behavior: smooth;
    }

    body{
        font-family:'Inter',sans-serif;
        background:linear-gradient(180deg,#f8fafc,#e2e8f0);
        min-height:100vh;
        overflow-y:auto;
    }

    .app{
        max-width:480px;
        margin:auto;
        min-height:100vh;
        display:flex;
        flex-direction:column;
        background:white;
        border-radius:25px;
        box-shadow:0 25px 60px rgba(0,0,0,0.12);
    }

    /* HEADER */
    .header{
        background:linear-gradient(135deg,#ef4444,#dc2626);
        color:white;
        padding:35px 20px 45px;
        border-bottom-left-radius:30px;
        border-bottom-right-radius:30px;
    }

    .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:12px;
        opacity:.85;
    }

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

    /* CARD TOTAL */
    .saldo-card{
        background:linear-gradient(135deg,#f43f5e,#ef4444);
        margin:-30px 20px 20px;
        padding:28px;
        border-radius:25px;
        color:white;
        box-shadow:0 15px 40px rgba(239,68,68,0.35);
    }

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

    .saldo-amount{
        font-size:38px;
        font-weight:800;
        margin:8px 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 - INI YANG PENTING UNTUK SCROLL */
    .content{
        flex:1;
        overflow-y:auto;
        padding:20px;
        padding-bottom:140px; /* Ruang untuk bottom nav */
        -webkit-overflow-scrolling:touch;
    }

    /* Custom Scrollbar */
    .content::-webkit-scrollbar {
        width: 4px;
    }
    .content::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
    .content::-webkit-scrollbar-thumb {
        background: #ef4444;
        border-radius: 2px;
    }
    .content::-webkit-scrollbar-thumb:hover {
        background: #dc2626;
    }

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

    /* FILTER */
    .calendar-filter{
        background:white;
        padding:18px;
        border-radius:18px;
        margin-bottom:20px;
        box-shadow:0 8px 20px rgba(0,0,0,0.05);
    }

    .calendar-header{
        display:flex;
        justify-content:space-between;
        align-items:center;
        margin-bottom:12px;
    }

    .calendar-title{
        font-size:15px;
        font-weight:700;
    }

    .calendar-nav{
        display:flex;
        gap:5px;
    }

    .calendar-btn{
        border:none;
        background:#f1f5f9;
        padding:6px 10px;
        border-radius:8px;
        font-size:12px;
        cursor:pointer;
        transition:.2s;
        text-decoration:none;
        color:#555;
    }

    .calendar-btn:hover{
        background:#e2e8f0;
    }

    /* MONTH BUTTON */
    .month-buttons{
        display:grid;
        grid-template-columns:repeat(6,1fr);
        gap:6px;
    }

    .month-btn{
        text-align:center;
        padding:8px;
        border-radius:8px;
        background:#f1f5f9;
        font-size:11px;
        color:#555;
        text-decoration:none;
        transition:.2s;
    }

    .month-btn:hover{
        background:#e2e8f0;
    }

    .month-btn.active{
        background:#ef4444;
        color:white;
        font-weight:600;
    }

    /* TABLE */
    .table-wrapper{
        background:white;
        border-radius:16px;
        box-shadow:0 8px 20px rgba(0,0,0,0.05);
        overflow:hidden;
        margin-top:15px;
    }

    .transaksi-table{
        width:100%;
        border-collapse:collapse;
        font-size:13px;
    }

    .transaksi-table th{
        background:#f1f5f9;
        padding:12px;
        text-align:left;
        font-size:12px;
        color:#555;
    }

    .transaksi-table td{
        padding:12px;
        border-bottom:1px solid #eee;
    }

    .transaksi-table tr:hover{
        background:#f8fafc;
    }

    .amount-expense{
        color:#dc2626;
        font-weight:700;
    }

    .table-actions{
        display:flex;
        gap:5px;
    }

    .table-delete{
        background:#fee2e2;
        color:#dc2626;
        padding:4px 6px;
        border-radius:6px;
        font-size:12px;
        text-decoration:none;
    }

    .table-delete:hover{
        background:#dc2626;
        color:white;
    }

    /* RANK BADGE */
    .rank-badge {
        min-width: 24px;
        height: 24px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 11px;
        font-weight: 700;
        margin-right: 8px;
    }

    .rank-1 { background: linear-gradient(135deg, #facc15, #eab308); color: #92400e; }
    .rank-2 { background: linear-gradient(135deg, #f3f4f6, #d1d5db); color: #374151; }
    .rank-3 { background: linear-gradient(135deg, #fbbf24, #f59e0b); color: #92400e; }

    /* BUTTONS */
    .export-btn, .filter-btn, .reset-btn {
        display:inline-block;
        padding:8px 14px;
        border-radius:8px;
        text-decoration:none;
        font-size:13px;
        font-weight:600;
        transition:.2s;
        border:none;
        cursor:pointer;
    }

    .export-btn {
        background:#16a34a;
        color:white;
    }

    .filter-btn {
        background:#ef4444;
        color:white;
    }

    .reset-btn {
        background:#f3f4f6;
        color:#ef4444;
    }

    /* FORM FILTER HARIAN */
    .filter-form {
        display:flex;
        gap:8px;
        flex-wrap:wrap;
        align-items:end;
    }

    .filter-date {
        flex:1;
        min-width:200px;
    }

    .filter-date label {
        font-size:12px;
        color:#555;
        display:block;
        margin-bottom:4px;
    }

    .filter-date input {
        width:100%;
        padding:8px;
        border-radius:8px;
        border:1px solid #ddd;
        font-size:13px;
    }

    /* EMPTY STATE */
    .empty-state{
        text-align:center;
        padding:50px 20px;
        color:#888;
    }

    /* NAVBAR - FIXED BOTTOM */
    .bottom-nav {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        max-width: 480px;
        margin: 0 auto;
        display: flex;
        justify-content: space-around;
        padding: 12px 0;
        border-top: 1px solid #eee;
        background: white;
        z-index: 999;
        box-shadow: 0 -5px 15px rgba(0,0,0,0.05);
    }

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

    .nav-item.active{
        color:#ef4444;
    }

    .nav-icon{
        font-size:22px;
        display:block;
        margin-bottom:3px;
    }

    .nav-item:hover{
        transform:translateY(-4px);
        color:#ef4444;
    }

    /* RESPONSIVE */
    @media (max-width: 480px) {
        .app {
            margin: 0;
            border-radius: 0;
            min-height: 100vh;
            height: 100vh;
        }
        
        .bottom-nav {
            max-width: 100%;
        }
    }
    </style>
</head>
<body>

<div class="app">
    <!-- HEADER -->
    <div class="header">
        <div class="header-top">
            <div class="user-info">
                <h1>Laporan Pengeluaran</h1>
                <p><b>Silaku</b></p>
            </div>
            <a href="index.php" class="back-btn">Kembali</a>
        </div>
    </div>

    <!-- SALDO CARD -->
    <div class="saldo-card">
        <div class="saldo-label">Total Pengeluaran</div>
        <div class="saldo-amount">Rp <?php echo number_format($total_pengeluaran, 0, ',', '.'); ?></div>
        <div class="saldo-stats">
            <div class="stat">
                <div class="stat-label">Jumlah Transaksi</div>
                <div class="stat-value"><?php echo $data_count; ?> Transaksi</div>
            </div>
            <div class="stat">
                <div class="stat-label">Rata-rata / Hari</div>
                <div class="stat-value">Rp <?php echo number_format($rata_harian, 0, ',', '.'); ?></div>
            </div>
        </div>
    </div>

    <!-- CONTENT - SEMUA KONTEN SCROLL DI SINI -->
    <div class="content">
        
        <!-- 1. KATEGORI RANKING -->
        <div class="calendar-filter">
            <div class="calendar-header">
                <div class="calendar-title">📊 Semua Kategori Pengeluaran</div>
                <div style="font-size:12px; color:#666;">
                    Total: <?php echo count($kategori_rank); ?> Kategori
                </div>
            </div>
            <div class="table-wrapper">
                <table class="transaksi-table">
                    <thead>
                        <tr>
                            <th>Rank</th>
                            <th>Kategori</th>
                            <th>Total</th>
                            <th>Transaksi</th>
                            <th>%</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($kategori_rank) > 0): ?>
                            <?php foreach($kategori_rank as $index => $row): 
                                $rank = $index + 1;
                                $persentase = $total_pengeluaran > 0 ? round(($row['total_kategori'] / $total_pengeluaran) * 100, 1) : 0;
                                $rank_class = '';
                                if($rank == 1) $rank_class = 'rank-1';
                                elseif($rank == 2) $rank_class = 'rank-2';
                                elseif($rank == 3) $rank_class = 'rank-3';
                            ?>
                            <tr>
                                <td><span class="rank-badge <?php echo $rank_class; ?>"><?php echo $rank; ?></span></td>
                                <td style="font-weight:600; max-width:150px;"><?php echo htmlspecialchars($row['keterangan']); ?></td>
                                <td class="amount-expense">Rp <?php echo number_format($row['total_kategori'],0,',','.'); ?></td>
                                <td><?php echo $row['jumlah_transaksi']; ?></td>
                                <td style="color:#059669; font-weight:600;"><?php echo $persentase; ?>%</td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" style="text-align:center;color:#888;padding:30px;">
                                    📭 Belum ada data kategori pengeluaran
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
<!-- Filter Harian Profesional -->
<div class="calendar-filter" style="margin-top:10px;">
    <form method="GET" id="filterHariForm" style="display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
        <div style="flex:1;">
            <label for="filterTanggal" style="font-size:12px; color:#555;">Pilih Tanggal:</label>
            <input type="date" id="filterTanggal" name="tanggal" value="<?php echo $tanggal_dipilih; ?>"
                style="width:100%; padding:8px; border-radius:8px; border:1px solid #ddd; font-size:13px;">
        </div>
        <div>
            <button type="submit" style="
                background:#ef4444;
                color:white;
                padding:10px 16px;
                border-radius:8px;
                font-size:13px;
                font-weight:600;
                border:none;
                cursor:pointer;
                transition:.2s;">
                🔍 Filter
            </button>
        </div>
        <?php if($tanggal_dipilih != ''){ ?>
        <div>
            <a href="laporan.php?bulan=<?php echo $bulan_dipilih; ?>&tahun=<?php echo $tahun_dipilih; ?>" 
               style="
               display:inline-block;
               background:#f3f4f6;
               color:#ef4444;
               padding:10px 16px;
               border-radius:8px;
               font-size:13px;
               font-weight:600;
               text-decoration:none;
               transition:.2s;">
               ✖ Reset
            </a>
        </div>
        <?php } ?>
    </form>
</div>

<!-- Reset filter -->
<?php if($tanggal_dipilih != ''){ ?>
    <a href="laporan.php?bulan=<?php echo $bulan_dipilih; ?>&tahun=<?php echo $tahun_dipilih; ?>" 
       style="display:block; margin-top:5px; font-size:12px; text-align:center; color:#ef4444; text-decoration:none;">
       Reset Filter
    </a>
<?php } ?>
        <!-- Filter Bulanan -->
        <div class="calendar-filter">
            <div class="calendar-header">
                <div class="calendar-title">
                    <?php 
                    $bulan_indo = array(
                        '01' => 'Januari', '02' => 'Februari', '03' => 'Maret',
                        '04' => 'April', '05' => 'Mei', '06' => 'Juni',
                        '07' => 'Juli', '08' => 'Agustus', '09' => 'September',
                        '10' => 'Oktober', '11' => 'November', '12' => 'Desember'
                    );
                    echo $bulan_indo[$bulan_dipilih] . ' ' . $tahun_dipilih;
                    ?>
                </div>
                <div class="calendar-nav">
                    <a href="?bulan=<?php echo date('m', strtotime('-1 month')); ?>&tahun=<?php echo date('Y', strtotime('-1 month')); ?>" class="calendar-btn">◀</a>
                    <a href="?bulan=<?php echo date('m'); ?>&tahun=<?php echo date('Y'); ?>" class="calendar-btn">Hari Ini</a>
                    <a href="?bulan=<?php echo date('m', strtotime('+1 month')); ?>&tahun=<?php echo date('Y', strtotime('+1 month')); ?>" class="calendar-btn">▶</a>
                </div>
            </div>
            <div class="month-buttons">
                <?php 
                $bulan_indo = array(
                    '01' => 'Jan', '02' => 'Feb', '03' => 'Mar',
                    '04' => 'Apr', '05' => 'Mei', '06' => 'Jun',
                    '07' => 'Jul', '08' => 'Agu', '09' => 'Sep',
                    '10' => 'Okt', '11' => 'Nov', '12' => 'Des'
                );
                for ($i = 1; $i <= 12; $i++) {
                    $bulan_str = str_pad($i, 2, '0', STR_PAD_LEFT);
                    $active = ($bulan_str == $bulan_dipilih) ? 'active' : '';
                    echo "<a href='?bulan=$bulan_str&tahun=$tahun_dipilih' class='month-btn $active'>" . $bulan_indo[$bulan_str] . "</a>";
                }
                ?>
            </div>
        </div>
        <div class="table-wrapper">

<table class="transaksi-table">

<thead>
<tr>
<th>Tanggal</th>
<th>Keterangan</th>
<th>Jumlah</th>
<th>Aksi</th>
</tr>
</thead>

<tbody>

<?php 
if ($data_count > 0) {

mysqli_data_seek($query, 0);

while ($row = mysqli_fetch_assoc($query)) {

echo "<tr>";

echo "<td>".date('d M Y', strtotime($row['tanggal']))."</td>";

echo "<td>".htmlspecialchars($row['keterangan'])."</td>";

echo "<td class='amount-expense'>- Rp ".number_format($row['jumlah'],0,',','.')."</td>";

echo "<td>
<a href='laporan.php?hapus=".$row['id']."' 
onclick='return confirm(\"Hapus transaksi ini?\")'
class='table-delete'>🗑️</a>
</td>";

echo "</tr>";

}

} else {

echo "<tr>";
echo "<td colspan='4' style='text-align:center;color:#888;padding:30px;'>Belum ada data</td>";
echo "</tr>";

}
?>

</tbody>

</table>

</div>
       
        </div>
    </div>

    <!-- Bottom Nav -->
   <div class="bottom-nav">

<a href="index.php" class="nav-item">
<span class="nav-icon">🏠</span>
Beranda
</a>

<a href="laporan.php" class="nav-item active">
<span class="nav-icon">📊</span>
Laporan
</a>

<a href="profil.php" class="nav-item">
<span class="nav-icon">👤</span>
Profil
</a>

</div>

</body>
</html>