<?php
require './kalenderhijriah.php';
error_reporting(E_ALL^(E_NOTICE|E_WARNING));
ini_set('display_errors',1);
error_reporting(0);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Tabungan</title>
    <!-- <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet"> -->
    <link rel="stylesheet" href="calendar.css"/>
    <style>
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --accent-color: #f093fb;
            --success-color: #4facfe;
            --warning-color: #ffecd2;
            --danger-color: #ff6b6b;
            --dark-color: #2c3e50;
            --light-color: #f8f9fa;
            --gradient-bg: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            --card-shadow: 0 10px 30px rgba(0,0,0,0.1);
            --card-radius: 15px;
        }

        body {
            background: linear-gradient(135deg,rgb(191, 198, 229) 0%, #764ba2 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            padding: 20px 0;
        }

        .main-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: var(--card-radius);
            box-shadow: var(--card-shadow);
            margin: 20px auto;
            max-width: 1400px;
            overflow: hidden;
        }

        .header-section {
            background: var(--gradient-bg);
            color: white;
            padding: 25px 30px;
            position: relative;
            overflow: hidden;
        }

        .header-section::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: rotate(45deg);
        }

        .header-title {
            font-size: 2rem;
            font-weight: 700;
            margin: 0;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .header-subtitle {
            opacity: 0.9;
            margin-top: 5px;
            font-size: 1.1rem;
        }

        .search-section {
            background: white;
            padding: 30px;
            border-bottom: 1px solid #eee;
        }

        .search-card {
            background: var(--light-color);
            border-radius: 12px;
            padding: 25px;
            border: 1px solid #e3e6f0;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }

        .form-control {
            border-radius: 8px;
            border: 2px solid #e3e6f0;
            padding: 12px 15px;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
            transform: translateY(-1px);
        }

        .btn-search {
            background: var(--gradient-bg);
            border: none;
            color: white;
            padding: 12px 25px;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-search:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            color: white;
        }

        .btn-pdf {
            background: linear-gradient(135deg,rgb(119, 117, 230) 0%,rgb(124, 211, 102) 100%);
            border: none;
            color: white;
            padding: 12px 25px;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(67, 233, 123, 0.3);
        }

        .btn-pdf:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(67, 233, 123, 0.4);
            color: white;
            text-decoration: none;
        }

        .datepicker-container {
            position: relative;
            display: inline-block;
        }

        .date-input-group {
            display: flex;
            align-items: center;
            background: white;
            border: 2px solid #e3e6f0;
            border-radius: 8px;
            padding: 5px;
            transition: all 0.3s ease;
        }

        .date-input-group:focus-within {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }

        .date-input {
            border: none;
            outline: none;
            padding: 7px 10px;
            width: 110px;
            font-size: 14px;
        }

        .calendar-icon {
            cursor: pointer;
            padding: 5px;
            color: var(--primary-color);
            transition: color 0.3s ease;
        }

        .calendar-icon:hover {
            color: var(--secondary-color);
        }

        .table-section {
            padding: 30px;
            background: white;
        }

        .modern-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: none;
        }

        .modern-table thead {
            background: var(--gradient-bg);
            color: white;
        }

        .modern-table thead th {
            border: none;
            padding: 18px 15px;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.5px;
            position: relative;
        }

        .modern-table tbody tr {
            transition: all 0.3s ease;
            border-bottom: 1px solid #f1f3f4;
        }

        .modern-table tbody tr:hover {
            background: rgba(102, 126, 234, 0.05);
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .modern-table tbody td {
            padding: 15px;
            border: none;
            vertical-align: middle;
            font-size: 14px;
        }

        .subtotal-row {
            background: linear-gradient(90deg, #f8f9ff 0%, #e8ecff 100%) !important;
            border-left: 4px solid var(--primary-color);
            font-weight: 600;
        }

        .total-row {
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%) !important;
            color: white;
            font-weight: 700;
            font-size: 15px;
        }

        .total-row td {
            border-top: 3px solid var(--primary-color);
        }

        .amount-cell {
            text-align: right;
            font-weight: 600;
            font-family: 'Courier New', monospace;
        }

        .positive-amount {
            color: #28a745;
        }

        .negative-amount {
            color: #dc3545;
        }

        .class-badge {
            background: var(--gradient-bg);
            color: white;
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .no-data {
            text-align: center;
            padding: 50px;
            color: #6c757d;
            font-style: italic;
        }

        .loading-spinner {
            display: none;
            text-align: center;
            padding: 30px;
        }

        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            border-left: 4px solid var(--primary-color);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-number {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 5px;
        }

        .stat-label {
            color: #6c757d;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .datepicker {
            position: absolute !important;
            z-index: 1050 !important;
            border-radius: 12px !important;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2) !important;
            border: none !important;
        }

        @media (max-width: 768px) {
            .main-container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header-section {
                padding: 20px;
            }
            
            .header-title {
                font-size: 1.5rem;
            }
            
            .search-section, .table-section {
                padding: 20px;
            }
            
            .modern-table {
                font-size: 12px;
            }
            
            .modern-table thead th,
            .modern-table tbody td {
                padding: 10px 8px;
            }
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="main-container fade-in">
            <!-- Header Section -->
            <div class="header-section">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h1 class="header-title">
                            <i class="fas fa-layer-group me-3"></i>
                            Laporan Tabungan
                        </h1>
                        <!-- <p class="header-subtitle mb-0">Sistem Informasi Keuangan</p> -->
                    </div>
                    <div class="text-end">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-calendar-alt me-2"></i>
                            <span><?php echo date('d F Y'); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Search Section -->
            <div class="search-section">
                <div class="search-card">
                    <?php
                    $username = $_SESSION['username'];
                    $kode = $_SESSION['kode']; 
                    if(isset($_POST['p_rekening'])){
                        $par1 = date('Y-m-d',strtotime($_POST['par1']));
                        $par2 = date('Y-m-d',strtotime($_POST['par2']));
                        $id = $_POST['p_rekening'];

                        if($_POST['p_rekening']!=='')
                            $where = "WHERE a.kode='$kode' AND a.rekening like '%".$id."%' OR b.nama like '%".$id."%' GROUP by a.no ";
                        else
                            $where = "WHERE a.tgl>='$par1' AND a.tgl<='$par2' GROUP by a.no ";
                    } else {
                        $id = "";
                        $where = "where a.rekening='$id' ";
                    }
                    ?>
                    
                    <form role="form" id="quickForm" action="home.php?home=<?php echo md5("mutasi_tabungan");?>" method="post">
                        <div class="row align-items-end g-3">
                            <div class="col-md-4">
                                <label class="form-label fw-semibold">
                                    <i class="fas fa-search me-2"></i>Pencarian Data
                                </label>
                                <input type="text" name="p_rekening" id="p_rekening" class="form-control" 
                                       placeholder="Ketik Register/Nama/Alamat/No Register/Ayah"
                                       value="<?php echo isset($_POST['p_rekening']) ? $_POST['p_rekening'] : ''; ?>">
                            </div>
                            
                            <div class="col-md-2" id="datepicker1">
                                <label class="form-label fw-semibold">Dari Tanggal</label>
                                <div class="datepicker-container">
                                    <div class="date-input-group"  id="datepicker">
                                        <input id="par1" name="par1" type="text" class="date-input" 
                                               value="<?php if(isset($_POST['par1'])){ echo $_POST['par1']; }else{ echo sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2];} ?>" />
                                        <i class="fas fa-calendar-alt calendar-icon" id="pick-button1"  alt="Pick Date" style="cursor: pointer; " onclick="pickADate1();" class="d-inline-block"></i>
                                    </div>
                                    <div id="calendar-popup1" class="datepicker" style="display:none;"></div>
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <label class="form-label fw-semibold">Sampai Tanggal</label>
                                <div class="datepicker-container">
                                    <div class="date-input-group" id="datepicker2">
                                        <input id="par2" name="par2" type="text" class="date-input" 
                                               value="<?php if(isset($_POST['par2'])){ echo $_POST['par2']; }else{ echo sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2];} ?>" />
                                        <i class="fas fa-calendar-alt calendar-icon" id="pick-button2" style="cursor: pointer;" onclick="pickADate2();" class="d-inline-block"></i>
                                    </div>
                                    <div id="calendar-popup2" class="datepicker" style="display:none;"></div>
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-search w-100">
                                    <i class="fas fa-search me-2"></i>Cari
                                </button>
                            </div>
                            
                            <?php if(isset($_POST['par1'])){ ?>
                            <div class="col-md-2">
                                <?php
                                $_SESSION['tabungan']['periode'] = date('d-m-Y',strtotime($_POST['par1'])). " S/d ". date('d-m-Y',strtotime($_POST['par2']));
                                $_SESSION['tabungan']['kantor'] = $_SESSION['kantor'];
                                ?>
                                <a href="pdf/lap_tabunganpdf.php" target="_blank" class="btn btn-pdf w-100">
                                    <i class="fas fa-file-pdf me-2"></i>Cetak PDF
                                </a>
                            </div>
                            <?php } ?>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Table Section -->
            <div class="table-section">
                <?php if(isset($_POST['par1'])){ ?>
                <!-- Stats Cards -->
                <div class="stats-cards mb-4">
                   <!--  <div class="stat-card">
                        <div class="stat-number"><?php echo date('d/m/Y', strtotime($_POST['par1'])); ?></div>
                        <div class="stat-label">Tanggal Mulai</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number"><?php echo date('d/m/Y', strtotime($_POST['par2'])); ?></div>
                        <div class="stat-label">Tanggal Akhir</div>
                    </div> -->
                    <div class="stat-card">
                        <div class="stat-number" id="total-records">0</div>
                        <div class="stat-label">Total Transaksi</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="total-amount">Rp 0</div>
                        <div class="stat-label">Total Nominal</div>
                    </div>
                </div>
                <?php } ?>

                <div class="table-responsive">
                    <table class="table modern-table" id="dataTable">
                        <thead>
                            <tr>
                                <th style="width: 60px;">No</th>
                                <th style="width: 120px;">Tanggal</th>
                                <th style="width: 120px;">No Bukti</th>
                                <th style="width: 150px;">Rekening</th>
                                <th>Nama</th>
                                <th style="width: 80px;">Kelas</th>
                                <th style="width: 120px;">Setor</th>
                                <th style="width: 120px;">Tarik</th>
                                <th>Keterangan</th>
                                <th style="width: 100px;">User</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            include 'koneksi.php';
                            $queryp = "SELECT b.klsNow as kls,a.no_bukti AS no_bukti,a.rekening as id, a.rekening as rekening, a.tgl as tgl, b.nama as nama, SUM(kredit-debet) AS saldotab, a.kredit AS kredit, a.debet AS debet, a.keterangan AS keterangan, a.username as username FROM mutasitabungan a LEFT JOIN registrasi b ON a.id=b.id $where ORDER BY b.klsNow, a.tgl";
                            $querya = mysqli_query($koneksi, $queryp);
                            
                            if (mysqli_num_rows($querya)) {
                                $_SESSION['tabungan']['kode']['sqlp'] = $queryp;
                                $no = 0;
                                $current_kls = '';
                                $kls_subtotal_kredit = 0;
                                $kls_subtotal_debet = 0;
                                $t_kredit = 0;
                                $t_debet = 0;
                                
                                while ($data = mysqli_fetch_assoc($querya)) {
                                    $tgl = $data['tgl'];
                                    $kls = $data['kls'];
                                    $no_bukti = $data['no_bukti'];
                                    $rekening = $data['rekening'];
                                    $nama = $data['nama'];
                                    $saldotab = $data['saldotab'];
                                    $keterangan = $data['keterangan'];
                                    $kredit = $data['kredit'];
                                    $debet = $data['debet'];
                                    $usersys = $data['username'];
                                    
                                    // Jika kelas berubah, tampilkan subtotal untuk kelas sebelumnya
                                    if ($current_kls != '' && $current_kls != $kls) {
                                        ?>
                                        <tr class="subtotal-row">
                                            <td colspan="6" class="text-center fw-bold">
                                                <i class="fas fa-layer-group me-2"></i>Jumlah Kelas <?php echo $current_kls; ?>
                                            </td>
                                            <td class="amount-cell positive-amount fw-bold"><?php echo number_format($kls_subtotal_kredit, 0); ?></td>
                                            <td class="amount-cell negative-amount fw-bold"><?php echo number_format($kls_subtotal_debet, 0); ?></td>
                                            <td colspan="2"></td>
                                        </tr>
                                        <?php
                                        // Reset subtotal untuk kelas baru
                                        $kls_subtotal_kredit = 0;
                                        $kls_subtotal_debet = 0;
                                    }
                                    
                                    // Update current class
                                    $current_kls = $kls;
                                    
                                    // Menambahkan ke subtotal
                                    $kls_subtotal_kredit += $kredit;
                                    $kls_subtotal_debet += $debet;
                                    
                                    // Menambahkan ke total keseluruhan
                                    $t_kredit += $kredit;
                                    $t_debet += $debet;
                                    
                                    $no++;
                            ?>
                                    <tr>
                                        <td class="text-center"><?php echo $no; ?></td>
                                        <td><?php echo date('d/m/Y', strtotime($tgl)); ?></td>
                                        <td><span class="badge bg-light text-dark"><?php echo $no_bukti; ?></span></td>
                                        <td><strong><?php echo $rekening; ?></strong></td>
                                        <td><?php echo $nama; ?></td>
                                        <td><span class="class-badge"><?php echo $kls; ?></span></td>
                                        <td class="amount-cell positive-amount"><?php echo $kredit > 0 ? number_format($kredit, 0) : '-'; ?></td>
                                        <td class="amount-cell negative-amount"><?php echo $debet > 0 ? number_format($debet, 0) : '-'; ?></td>
                                        <td><?php echo $keterangan; ?></td>
                                        <td><span class="badge bg-primary"><?php echo $usersys; ?></span></td>
                                    </tr>
                            <?php
                                }
                                
                                // Tampilkan subtotal untuk kelas terakhir
                                if ($current_kls != '') {
                                    ?>
                                    <tr class="subtotal-row">
                                        <td colspan="6" class="text-center fw-bold">
                                            <i class="fas fa-layer-group me-2"></i>Subtotal Kelas <?php echo $current_kls; ?>
                                        </td>
                                        <td class="amount-cell positive-amount fw-bold"><?php echo number_format($kls_subtotal_kredit, 0); ?></td>
                                        <td class="amount-cell negative-amount fw-bold"><?php echo number_format($kls_subtotal_debet, 0); ?></td>
                                        <td colspan="2"></td>
                                    </tr>
                                    <?php
                                }
                            } else {
                                ?>
                                <tr>
                                    <td colspan="10" class="no-data">
                                        <i class="fas fa-inbox fa-3x mb-3 text-muted"></i>
                                        <br>Tidak ada data yang ditemukan
                                    </td>
                                </tr>
                                <?php
                            }
                            ?>
                        </tbody>
                        <?php if(isset($t_kredit) && isset($t_debet)) { ?>
                        <tfoot>
                            <tr class="total-row">
                                <td colspan="6" class="text-center fw-bold">
                                    <i class="fas fa-calculator me-2"></i>TOTAL KESELURUHAN
                                </td>
                                <td class="amount-cell fw-bold"><?php echo number_format($t_kredit, 0); ?></td>
                                <td class="amount-cell fw-bold"><?php echo number_format($t_debet, 0); ?></td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                        <?php } ?>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script> -->
   <link rel="stylesheet" href="calendar.css"/>
<script type="text/javascript" src="hijri-date.js"></script>
<script type="text/javascript" src="calendar.js"></script>

    <script type="text/javascript">
    var pickedTxt1 = document.getElementById('par1'),
        datepicker1 = new Calendar(true, 0, false, true);
    document.getElementById('datepicker1').appendChild(datepicker1.getElement());
    datepicker1.getElement().style.marginTop = '10px';
    
    datepicker1.callback = function() {
        var selectedDate = datepicker1.getDate();
        var day = selectedDate.getDate().toString().padStart(2, '0');
        var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        var year = selectedDate.getFullYear();
        pickedTxt1.value = day + '-' + month + '-' + year;
        pickedTxt1.selectionStart = 0;
        pickedTxt1.selectionEnd = pickedTxt1.value.length;
        pickedTxt1.focus();
        datepicker1.hide();
    };

    function pickADate1() {
        datepicker1.show();
        datepicker1.getElement().style.position = 'absolute'; // Pastikan posisi kalender tidak mengganggu layout
    }

    var pickedTxt2 = document.getElementById('par2'),
        datepicker2 = new Calendar(true, 0, false, true);
    document.getElementById('datepicker2').appendChild(datepicker2.getElement());
    datepicker2.getElement().style.marginTop = '10px';
    
    datepicker2.callback = function() {
        var selectedDate = datepicker2.getDate();
        var day = selectedDate.getDate().toString().padStart(2, '0');
        var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        var year = selectedDate.getFullYear();
        pickedTxt2.value = day + '-' + month + '-' + year;
        pickedTxt2.selectionStart = 0;
        pickedTxt2.selectionEnd = pickedTxt2.value.length;
        pickedTxt2.focus();
        datepicker2.hide();
    };

    function pickADate2() {
        datepicker2.show();
        datepicker2.getElement().style.position = 'absolute'; // Pastikan posisi kalender tidak mengganggu layout
    }
</script>
<style>
    /* Mengatur posisi datepicker agar tidak mempengaruhi layout lain */
    .datepicker {
        position: absolute; /* Mencegah pergeseran elemen lain */
        z-index: 1000; /* Agar kalender muncul di atas elemen lain */
    }
</style>
<script type="text/javascript">
function addClickOutsideListener(datepicker, popupId) {
        function onClick(event) {
            var popup = document.getElementById(popupId);
            if (popup && !popup.contains(event.target) && !datepicker.getElement().contains(event.target)) {
               
                datepicker.hide(); // Menyembunyikan kalender
                document.removeEventListener('click', onClick); // Menghapus event listener setelah digunakan
            }
        }
        
        // Menambahkan event listener untuk mendeteksi klik di luar kalender
        document.addEventListener('click', onClick);
    }


        // Update stats
        document.addEventListener('DOMContentLoaded', function() {
            var table = document.getElementById('dataTable');
            var rows = table.querySelectorAll('tbody tr:not(.subtotal-row)');
            var totalRecords = rows.length;
            
            // Update total records
            var totalRecordsElement = document.getElementById('total-records');
            if (totalRecordsElement) {
                totalRecordsElement.textContent = totalRecords;
            }
            
            // Calculate total amount
            var totalAmount = 0;
            rows.forEach(function(row) {
                var cells = row.querySelectorAll('td');
                if (cells.length > 6) {
                    var kredit = cells[6].textContent.replace(/[^0-9]/g, '') || '0';
                    var debet = cells[7].textContent.replace(/[^0-9]/g, '') || '0';
                    totalAmount += parseInt(kredit) - parseInt(debet);
                }
            });
            
            var totalAmountElement = document.getElementById('total-amount');
            if (totalAmountElement) {
                totalAmountElement.textContent = 'Rp ' + totalAmount.toLocaleString('id-ID');
            }
        });

        // Add loading effect to form submission
        document.getElementById('quickForm').addEventListener('submit', function() {
            var btn = this.querySelector('button[type="submit"]');
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Mencari...';
            btn.disabled = true;
        });
    </script>
</body>
</html>