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

// Proses penyimpanan data ke tabel message
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['proses_data'])) {

// kirim Wa Langsung semua tagihan

    $dataTable = mysqli_real_escape_string($koneksi, $_POST['dataTable']);
    $statusBayar = mysqli_real_escape_string($koneksi, $_POST['statusBayar']);
    $bulaN = mysqli_real_escape_string($koneksi, date('m', strtotime($_POST['par2'])));
    $tahuN = mysqli_real_escape_string($koneksi, date('Y', strtotime($_POST['par2'])));
    
    // Validasi input yang diperlukan
    if (empty($dataTable) || empty($statusBayar) || empty($tahuN)) {
        $message = "? Data input tidak lengkap.";
        $alert_type = "danger";
    } else {
        // Build where condition sama seperti query utama
        $where = " WHERE 1=1 ";
        $groupBy = " GROUP BY a.id ";
        
        if ($statusBayar == "lunas") {
            $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
            $having = " HAVING SUM(a.bayar) >= SUM(a.kewajiban)";
        } elseif ($statusBayar == "bayar") {
            $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
            $having = " HAVING SUM(a.bayar) > 0 AND SUM(a.bayar) < SUM(a.kewajiban)";
        } else { // belum bayar
            $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
            $having = "  HAVING SUM(a.bayar) < SUM(a.kewajiban)";
        }
        
        // Query untuk mengambil data yang akan diproses
        $queryProses = "SELECT a.id AS id, a.nim AS nim, b.nama AS nama, a.tglmasehi AS tglmasehi, 
                MONTH(a.tglmasehi) AS month1, YEAR(a.tglmasehi) AS year1, a.no_kls AS no_kls, 
                a.tahun, a.bulan, SUM(a.kewajiban) AS kewajiban, SUM(a.bayar) AS bayar, 
                SUM(a.bayar - a.kewajiban) AS sisa, a.keterangan AS keterangan, a.username AS username,
                b.nohp AS nohp
                FROM $dataTable a 
                LEFT JOIN registrasi b ON a.id = b.id 
                $where $groupBy $having";
        
        // Debug query jika diperlukan
        // error_log("Query Proses: " . $queryProses);
        
        $resultProses = mysqli_query($koneksi, $queryProses);
        
        if (!$resultProses) {
            $message = "? Error dalam query data: " . mysqli_error($koneksi);
            $alert_type = "danger";
        } elseif (mysqli_num_rows($resultProses) > 0) {
            $berhasil = 0;
            $gagal = 0;
            $error_messages = [];
            
            // Begin transaction untuk memastikan konsistensi data
            mysqli_autocommit($koneksi, FALSE);
            
            // Array untuk mapping bulan
            $BulanH = [
                "10" => "Syawal",
                "11" => "Dz. Qodah",
                "12" => "Dz Hijjah",
                "01" => "Muharram",
                "02" => "Shafar",
                "03" => "R. Awal",
                "04" => "R. Tsani",
                "05" => "J. Ula",
                "06" => "J. Tsani",
                "07" => "Rajab",
                "08" => "Sy`aban",
                "09" => "Ramadhan",
            ];
            
            while ($row = mysqli_fetch_assoc($resultProses)) {
                // Validasi dan sanitasi data dengan nilai default
                $nohp = mysqli_real_escape_string($koneksi, 
                    !empty($row['nohp']) ? $row['nohp'] : '0000000000');
                $tglmasehi2 = $hijri[2]. '-' . $calendar->monthName($hijri[0]). '-' . sprintf('%02d', $hijri[1]);
                $kls = mysqli_real_escape_string($koneksi, 
                    !empty($row['no_kls']) ? $row['no_kls'] : 'N/A');
                $penErima = mysqli_real_escape_string($koneksi, 
                    !empty($row['nama']) ? $row['nama'] : 'Unknown');
                $kantor = 'System';
                $nim = mysqli_real_escape_string($koneksi, 
                    !empty($row['nim']) ? $row['nim'] : 'N/A');
                $judul = "MMU A-39";
                $tagihan = "*TAGIHAN ". strtoupper($dataTable)."*";
                
                // Konversi dan validasi angka
                $kewajiban = is_numeric($row['kewajiban']) ? (float)$row['kewajiban'] : 0.0;
                $sisaKewajiban = is_numeric($row['sisa']) ? (float)$row['sisa'] : 0.0;
                $bayar = is_numeric($row['bayar']) ? (float)$row['bayar'] : 0.0;
                
                $keteranganpesan = mysqli_real_escape_string($koneksi, 
                    "" . ucfirst($dataTable) . " - " . 
                    (!empty($row['keterangan']) ? $row['keterangan'] : 'No Description'));
                
                // Cek apakah data sudah ada untuk mencegah duplikasi
                $checkDuplicate = "SELECT COUNT(*) as count FROM message_tes 
                                 WHERE rekening = '$nim' 
                                 AND penErima = '$penErima' 
                                 AND keterangan = '$keteranganpesan'
                                 AND DATE(tgl) = CURDATE()";
                
                $duplicateResult = mysqli_query($koneksi, $checkDuplicate);
                $duplicateCount = mysqli_fetch_assoc($duplicateResult)['count'];
                
                if ($duplicateCount > 0) {
                    $gagal++;
                    $error_messages[] = "Data untuk NIM $nim sudah ada hari ini";
                    continue;
                }
                
                // Insert ke tabel message dengan prepared statement untuk keamanan
                $insertQuery = "INSERT INTO message_tes
                               (number, tgl, judul, penErima, PenGirim, rekening, kewajiban, sisaKewajiban, nominal, keterangan, metodeBayar, kodeFilTer) 
                               VALUES 
                               (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '$tagihan', 'Syahriah')";
                
                $stmt = mysqli_prepare($koneksi, $insertQuery);
                
                if ($stmt) {
                    mysqli_stmt_bind_param($stmt, "ssssssddds", 
                        $nohp, $tglmasehi2, $judul, $penErima, $kls, 
                        $nim, $kewajiban, $bayar, $sisaKewajiban, $keteranganpesan);
                    
                    $waTagihan = mysqli_stmt_execute($stmt);
                    
                    if ($waTagihan) {
                        $berhasil++;
                    } else {
                        $gagal++;
                        $error_messages[] = "Error insert untuk NIM $nim: " . mysqli_stmt_error($stmt);
                    }
                    
                    mysqli_stmt_close($stmt);
                } else {
                    $gagal++;
                    $error_messages[] = "Error prepare statement untuk NIM $nim: " . mysqli_error($koneksi);
                }
            }
            
            // Commit atau rollback transaksi
            if ($berhasil > 0 && $gagal == 0) {
                mysqli_commit($koneksi);
                $message = "? Berhasil memproses $berhasil data ke tabel message.";
                $alert_type = "success";
            } elseif ($berhasil > 0 && $gagal > 0) {
                mysqli_commit($koneksi);
                $message = "?? Berhasil memproses $berhasil data, $gagal data gagal diproses.";
                if (!empty($error_messages)) {
                    $message .= "<br>Detail error: " . implode(", ", array_slice($error_messages, 0, 3));
                    if (count($error_messages) > 3) {
                        $message .= " dan " . (count($error_messages) - 3) . " error lainnya.";
                    }
                }
                $alert_type = "warning";
            } else {
                mysqli_rollback($koneksi);
                $message = "? Gagal memproses semua data ke tabel message.";
                if (!empty($error_messages)) {
                    $message .= "<br>Detail error: " . implode(", ", array_slice($error_messages, 0, 3));
                }
                $alert_type = "danger";
            }
            
            // Restore autocommit
            mysqli_autocommit($koneksi, TRUE);
            
        } else {
            $message = "?? Tidak ada data yang ditemukan untuk diproses dengan kriteria yang diberikan.";
            $alert_type = "warning";
        }
    }
}

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Pembayaran Syahriah</title>
    
    <!-- CSS styles sama seperti sebelumnya -->
    <link rel="stylesheet" href="calendar.css" />
    
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            --info-gradient: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            --warning-gradient: linear-gradient(135deg, #f39c12 0%, #e74c3c 100%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            --glass-bg: rgba(255, 255, 255, 0.1);
            --glass-border: rgba(255, 255, 255, 0.2);
        }

        .main-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin: 20px;
            overflow: hidden;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .page-header {
            background: var(--primary-gradient);
            color: white;
            padding: 8px;
            position: relative;
            overflow: hidden;
        }

        .page-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin: 0;
            position: relative;
            z-index: 1;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .card-modern {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            border: none;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .filter-section {
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 1px;
            border: 1px solid var(--glass-border);
        }

        .form-control-modern {
            background: rgba(255, 255, 255, 0.9);
            border: 2px solid rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            padding: 12px 18px;
            font-size: 14px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .form-control-modern:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
            background: rgba(255, 255, 255, 1);
        }

        .btn-modern {
            border: none;
            border-radius: 12px;
            padding: 12px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .btn-modern::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .btn-modern:hover::before {
            left: 100%;
        }

        .btn-primary-modern {
            background: var(--primary-gradient);
            color: white;
        }

        .btn-success-modern {
            background: var(--success-gradient);
            color: white;
        }

        .btn-info-modern {
            background: var(--info-gradient);
            color: white;
        }

        .btn-secondary-modern {
            background: var(--dark-gradient);
            color: white;
        }

        .btn-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
        }

        .control-panel {
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 10px;
            margin-bottom: 5px;
            border: 1px solid var(--glass-border);
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }

        .stats-badge {
            background: var(--info-gradient);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .table-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .table-modern {
            margin: 0;
            background: transparent;
        }

        .table-modern thead th {
            background: var(--primary-gradient);
            color: white;
            border: none;
            padding: 18px 15px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .table-modern tbody tr {
            transition: all 0.3s ease;
        }

        .table-modern tbody tr:hover {
            background: rgba(102, 126, 234, 0.1);
            transform: scale(1.01);
        }

        .table-modern tbody td {
            padding: 15px;
            vertical-align: middle;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .total-row {
            background: var(--dark-gradient);
            color: white;
            font-weight: 700;
        }

        .total-row td {
            border: none;
            padding: 20px 15px;
        }

        .number-format {
            font-family: 'Courier New', monospace;
            font-weight: 600;
        }

        .datepicker-container {
            position: relative;
            display: flex;
            align-items: center;
        }

        .datepicker-input {
            padding-right: 3.5rem !important;
        }

        .datepicker-btn {
            background: var(--info-gradient);
            border: none;
            border-radius: 10px;
            padding: 12px;
            margin-left: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .datepicker-btn:hover {
            transform: scale(1.1);
        }

        .floating-action {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
        }

        .export-btn {
            background: var(--success-gradient);
            border: none;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            color: white;
            font-size: 24px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
        }

        .export-btn:hover {
            transform: scale(1.1) rotate(10deg);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid transparent;
            border-radius: 15px;
            backdrop-filter: blur(10px);
        }

        .alert-success {
            background: rgba(40, 167, 69, 0.1);
            border-color: rgba(40, 167, 69, 0.3);
            color: #155724;
        }

        .alert-warning {
            background: rgba(255, 193, 7, 0.1);
            border-color: rgba(255, 193, 7, 0.3);
            color: #856404;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-color: rgba(220, 53, 69, 0.3);
            color: #721c24;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .page-title {
                font-size: 1.8rem;
            }
            
            .main-container {
                margin: 10px;
                border-radius: 15px;
            }
            
            .control-panel {
                flex-direction: column;
                align-items: stretch;
            }
            
            .btn-modern {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>

<body>
    <div class="main-container">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-chart-line"></i>
                Laporan Pembayaran <?php if(isset($_POST['dataTable'])){echo ucfirst($_POST['dataTable']); }?>
            </h1>
        </div>

        <div class="container-fluid p-4">
            <?php
            // Tampilkan pesan alert jika ada
            if (isset($message) && isset($alert_type)) {
                echo "<div class='alert alert-$alert_type alert-dismissible fade show' role='alert'>
                        $message
                        <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                      </div>";
            }
            
            // Initialize the variables
            $username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
            $kode = isset($_SESSION['kode']) ? $_SESSION['kode'] : '';
            $dataTable = ''; // Initialize to avoid undefined variable
            $statusBayar = '';
            $par1 = '';
            $par2 = '';
            $where = " WHERE 1=1 ";          
                      
            $username = $_SESSION['username'];
            $kode = $_SESSION['kode'];

            $dataTable = $_POST['dataTable'] ?? ''; 

            if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['dataTable'])) {
              $dataTable = $_POST['dataTable'];
              $statusBayar = $_POST['statusBayar'];
              $par1 = mysqli_real_escape_string($koneksi, date('Y-m-d',strtotime($_POST['par1'])));
              $par2 = mysqli_real_escape_string($koneksi, date('Y-m-d',strtotime($_POST['par2'])));
              $bulaN = mysqli_real_escape_string($koneksi, date('m',strtotime($_POST['par2'])));
              $tahuN = mysqli_real_escape_string($koneksi, date('Y',strtotime($_POST['par2'])));
              $tglHitung = [
                "10" => 1,
                "11" => 2,
                "12" => 3,
                "01" => 4,
                "02" => 5,
                "03" => 6,
                "04" => 7,
                "05" => 8,
                "06" => 9,
                "07" => 10,
                "08" => 11,
                "09" => 12
            ];

            $where = " WHERE 1=1 ";
            $groupBy = " GROUP BY a.rekGabung, a.tahun ";
            
            if ($statusBayar == "lunas") {
                $where .= "AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
                $having = " HAVING SUM(a.bayar) >= SUM(a.kewajiban) ";
            } elseif ($statusBayar == "bayar") {
                $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
                $having = " HAVING SUM(a.bayar) > 0 AND SUM(a.bayar) < SUM(a.kewajiban) ";
            } else {
                $where .= " AND DATE_FORMAT(a.tglmasehi, '%Y-%m') <= CONCAT('$tahuN', '-', '$bulaN') ";
                $having = " HAVING SUM(a.bayar) = 0 ";
            }
        } else {
            $where .= " AND 1=0 ";
        }
        
        $sBayaR = [
          "lunas" => "Lunas",
          "bayar" => "Bayar",
          "tidak" => "Tidak Bayar"
        ];
        
        $BulanH = [
          "10" => "Syawal",
          "11" => "Dz. Qodah",
          "12" => "Dz Hijjah",
          "01" => "Muharram",
          "02" => "Shafar",
          "03" => "R. Awal",
          "04" => "R. Tsani",
          "05" => "J. Ula",
          "06" => "J. Tsani",
          "07" => "Rajab",
          "08" => "Sy`aban",
          "09" => "Ramadhan",
        ];
        ?>
        
        <!-- Filter Section -->
        <div class="filter-section">
            <form role="form" id="quickForm" action="home.php?home=<?php echo md5("lapbayar_syahriah");?>" method="POST">
                <div class="row align-items-end">
                    <div class="col-md-3">
                        <label class="form-label">Status Bayar</label>
                        <input type="hidden" name="dataTable" id="dataTable" value="bulanan">              
                        <select class="form-control form-control-modern" name="statusBayar" id="statusBayar">                          
                            <option><?php if(isset($_POST['statusBayar'])){ echo $sBayaR[$_POST['statusBayar']]; }else{echo "PILIH STATUS";}?></option>
                            <option value="lunas">Lunas</option>
                            <option value="bayar">Bayar</option>
                            <option value="tidak">Tidak Bayar</option>                  
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">Periode</label>
                        <div class="datepicker-container">
                            <input id="par2" name="par2" type="text" class="form-control datepicker-input" 
                                   value="<?php if(isset($_POST['par2'])){ echo $_POST['par2']; }else{ echo sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2];} ?>" />
                            <button type="button" class="datepicker-btn" onclick="pickADate2();">
                                <i class="fas fa-calendar-alt text-white"></i>
                            </button>
                            <div id="calendar-popup2" class="datepicker" style="display:none;"></div>
                        </div>   
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-modern btn-primary-modern w-100">
                            <i class="fas fa-search me-2"></i>Cari
                        </button>
                    </div>
                    
                    <?php if(isset($_POST['par2'])){?>
                    <div class="col-md-2">
                        <?php
                        $_SESSION['bayar_kewajiban']['periode'] = date('d-m-Y',strtotime($_POST['par1'])). " S/d ". date('d-m-Y',strtotime($_POST['par2']));
                        $_SESSION['bayar_kewajiban']['namaKewajiban'] = $dataTable; 
                        ?>
                        <a href="exportexcell/bayar_syahriah_murid.php" target="_blank" 
                           class="btn btn-modern btn-success-modern w-100" title="Download Excel">
                            <i class="fas fa-file-excel me-2"></i>Excel
                        </a>
                    </div>
                    <?php } ?>
                </div>
            </form>
        </div>
        

        <!-- Control Panel -->
        <div class="control-panel">
            <div class="d-flex flex-wrap gap-2">
                <!-- Form untuk proses data tanpa checkbox -->
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="dataTable" value="<?php echo $dataTable; ?>">
                    <input type="hidden" name="statusBayar" value="<?php echo $statusBayar; ?>">
                    <input type="hidden" name="par2" value="<?php echo $_POST['par2'] ?? ''; ?>">
                    <button type="submit" name="proses_data" class="btn btn-modern btn-success-modern" 
                            <?php echo (isset($_POST['dataTable']) && !empty($_POST['dataTable'])) ? '' : 'disabled'; ?>>
                        <i class="fas fa-paper-plane me-2"></i>Kirim WA
                    </button>
                </form>
            </div>
            <?php if(isset($_POST['dataTable']) && !empty($_POST['dataTable'])) { ?>
                <?php
                 $DeleteWA = mysqli_query($koneksi, "DELETE FROM message WHERE status='1' OR status='2' ") or die(mysqli_error($koneksi));
                ?>
            <!-- <div class="ms-auto">
                <span class="stats-badge">
                    <i class="fas fa-database"></i>
                    Siap diproses
                </span>
            </div> -->
            <?php } ?>
        </div>

        <!-- Data Table -->
        <div class="table-container">
            <table id="sortTable" class="table table-modern">
                <thead>
                    <tr>
                        <th>No</th>
                       <th>ID</th>
                        <th>NIM</th>
                        <th>Bln</th>
                        <th>Nama</th>           
                        <th>Kewajiban</th>
                        <th>Bayar</th>
                        <th>Sisa</th>
                        <th>Kls</th>
                        <th>Keterangan</th>
                    </tr>
                </thead>
                        <tbody>
                            <?php
                            include 'koneksi.php';
                            if (!empty($dataTable)) { // Check if $dataTable is not empty
                                $queryba = "SELECT a.id AS id, a.nim AS nim, b.nama AS nama, a.tglmasehi AS tglmasehi, 
                                MONTH(a.tglmasehi) AS month1, YEAR(a.tglmasehi) AS year1, a.no_kls AS no_kls, a.tahun,a.bulan,
                                sum(a.kewajiban) AS kewajiban, SUM(a.bayar) AS bayar, sum(a.kewajiban-a.bayar) AS sisa, a.keterangan AS keterangan, a.username AS username,
                                b.nohp AS nohp
                                FROM $dataTable a 
                                LEFT JOIN registrasi b ON a.id = b.id 
                                 $where $groupBy $having";
                            $querya = mysqli_query($koneksi, $queryba);
                            $_SESSION['bayar_syahriah']['kode']['sqlbyr']=$queryba;

                            if ($querya) {
                                $t_kewajiban = 0;
                                $t_bayar = 0;
                                $t_sisa = 0;
                                $no = 0;

                                if (mysqli_num_rows($querya) > 0) {
                                    while ($barisD = mysqli_fetch_assoc($querya)) {
                                        $kewajiban = $barisD['kewajiban'];
                                        $bayar = $barisD['bayar'];
                                        $sisa = $bayar-$kewajiban;
                                        $t_kewajiban += $barisD['kewajiban'];
                                        $t_bayar += $barisD['bayar'];
                                        $t_sisa = $t_bayar-$t_kewajiban;
                                        $no++;
                                        
                                        // Data untuk checkbox - format: nim|nama|kewajiban|bayar|bulan|kls|nohp
                                        $checkbox_data = $barisD['nim'] . '|' . $barisD['nama'] . '|' . $barisD['kewajiban'] . '|' . $barisD['bayar'] . '|' . $BulanH[$barisD['bulan']] . '|' . $barisD['no_kls'] . '|' . ($barisD['nohp'] ?? '');
                                        ?>
                                        <tr>
                                           <!--  <td align="center">
                                                <input type="checkbox" name="selected_data[]" value="<?php echo htmlspecialchars($checkbox_data); ?>" class="row-checkbox checkbox-modern">
                                            </td> -->
                                            <td align="center"><?php echo $no; ?></td>
                                            <td><?php echo $barisD['id']; ?></td>
                                            <td><?php echo $barisD['nim']; ?></td>
                                           
                                            <td><?php echo $BulanH[$barisD['bulan']]; ?></td>
                                            <td><?php echo $barisD['nama']; ?></td>
                                            <td align="right" class="number-format"><?php echo number_format($barisD['kewajiban'], 0); ?></td>
                                            <td align="right" class="number-format"><?php echo number_format($barisD['bayar'], 0); ?></td>
                                            <td align="right" class="number-format"><?php echo number_format($sisa, 0); ?></td>
                                            <td><?php echo $barisD['no_kls']; ?></td>
                                            <td><?php echo $barisD['keterangan']; ?></td>
                                           <td><?php echo $barisD['no_kls']; ?></td>
                                        </tr>
                                        <?php
                                    }
                                } else {
                                    echo "<tr><td colspan='12' align='center'><div class='text-muted py-4'><i class='fas fa-inbox fa-3x mb-3'></i><br>Tidak ada data yang ditemukan</div></td></tr>";
                                }
                            } else {
                                echo "<tr><td colspan='12' align='center'><div class='text-danger py-4'><i class='fas fa-exclamation-triangle fa-3x mb-3'></i><br>Error executing query: " . mysqli_error($koneksi) . "</div></td></tr>";
                            }
                        } else {
                            echo "<tr><td colspan='12' align='center'><div class='text-warning py-4'><i class='fas fa-search fa-3x mb-3'></i><br>Silakan pilih kriteria pencarian terlebih dahulu</div></td></tr>";
                        }
                        ?>
                        </tbody>
                        
                        <tfoot class="total-row">
                            <tr>
                                <td colspan="7"><strong><i class="fas fa-calculator me-2"></i>Total Keseluruhan</strong></td>
                                <td align="right" class="number-format"><strong><?php echo number_format($t_kewajiban ?? 0, 0); ?></strong></td>
                                <td align="right" class="number-format"><strong><?php echo number_format($t_bayar ?? 0, 0); ?></strong></td>
                                <td align="right" class="number-format"><strong><?php echo number_format($t_sisa ?? 0, 0); ?></strong></td>
                                <td colspan="2"></td>
                            </tr> 
                        </tfoot>
                    </table>
                </form>
            </div>
        </div>
    </div>

    <!-- Floating Export Button -->
    <?php if(isset($_POST['par2'])){?>
    <div class="floating-action">
        <a href="exportexcell/bayar_syahriah_murid.php" target="_blank" class="btn export-btn" title="Export to Excel">
            <i class="fas fa-download"></i>
        </a>
    </div>
    <?php } ?>
        
                 <script type="text/javascript" charset="utf8" src="./assets/jquery.dataTables.js"></script>
                  
                  <link rel="stylesheet" type="text/css" href="./assets/jquery.dataTables.css">
                      <script>
                  $('#sortTable').DataTable(); //https://www.sahretech.com/2020/04/cara-membuat-pencarian-sorting-dan.html?m=1/ cara buat sorter table
                  </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 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';
        }
    </script>

    <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();
                    document.removeEventListener('click', onClick);
                }
            }
            document.addEventListener('click', onClick);
        }

    // JavaScript untuk mengelola checkbox dan tombol proses
    $(document).ready(function() {
        // Master checkbox
        $('#masterCheck').on('change', function() {
            $('.row-checkbox').prop('checked', this.checked);
            updateSelectedCount();
        });

        // Individual checkbox
        $('.row-checkbox').on('change', function() {
            updateSelectedCount();
            
            // Update master checkbox
            var totalCheckboxes = $('.row-checkbox').length;
            var checkedCheckboxes = $('.row-checkbox:checked').length;
            
            if (checkedCheckboxes === 0) {
                $('#masterCheck').prop('indeterminate', false);
                $('#masterCheck').prop('checked', false);
            } else if (checkedCheckboxes === totalCheckboxes) {
                $('#masterCheck').prop('indeterminate', false);
                $('#masterCheck').prop('checked', true);
            } else {
                $('#masterCheck').prop('indeterminate', true);
            }
        });

        // Tombol pilih semua
        $('#selectAll').on('click', function() {
            $('.row-checkbox').prop('checked', true);
            $('#masterCheck').prop('checked', true);
            updateSelectedCount();
        });

        // Tombol batal pilih
        $('#deselectAll').on('click', function() {
            $('.row-checkbox').prop('checked', false);
            $('#masterCheck').prop('checked', false);
            updateSelectedCount();
        });

        // Update jumlah item yang dipilih
        function updateSelectedCount() {
            var count = $('.row-checkbox:checked').length;
            $('#selectedCount').text(count + ' dipilih');
            
            // Enable/disable tombol proses
            if (count > 0) {
                $('#prosesBtn').prop('disabled', false);
            } else {
                $('#prosesBtn').prop('disabled', true);
            }
        }

        // Konfirmasi sebelum memproses
        $('#prosesForm').on('submit', function(e) {
            var count = $('.row-checkbox:checked').length;
            if (count === 0) {
                e.preventDefault();
                alert('Pilih minimal satu data untuk diproses!');
                return false;
            }
            
            if (!confirm('Apakah Anda yakin ingin memproses ' + count + ' data yang dipilih?')) {
                e.preventDefault();
                return false;
            }
        });

        // Initial count update
        updateSelectedCount();
    });
    </script>

    <style>
        .datepicker {
            position: absolute;
            z-index: 1000;
        }
        
        .row-checkbox {
            cursor: pointer;
        }
        
        #selectedCount {
            font-size: 12px;
        }
        
        #prosesBtn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
    </style>

</body>
</html>