<?php
session_start();

// Enhanced error handling and security
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in production

// Security check - ensure user is logged in
if (!isset($_SESSION['username']) || !isset($_SESSION['kode'])) {
    header('Location: login.php');
    exit();
}

include 'koneksi.php';
require './kalenderhijriah.php';

// Initialize variables with proper defaults
$username = $_SESSION['username'];
$kode = $_SESSION['kode'];
$dataTable = '';
$statusBayar = '';
$par1 = '';
$par2 = '';
$where = " WHERE 1=1 ";
$queryExecuted = false;

// Enhanced input validation and sanitization
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['dataTable'])) {
    // Validate and sanitize inputs
    $allowedTables = ['bulanan', 'iktibar', 'kitab', 'imda1', 'imda2', 'imda3'];
    $allowedStatus = ['lunas', 'bayar', 'tidak'];
    
    $dataTable = in_array($_POST['dataTable'], $allowedTables) ? $_POST['dataTable'] : '';
    $statusBayar = in_array($_POST['statusBayar'], $allowedStatus) ? $_POST['statusBayar'] : '';
    
    // Enhanced date validation
    if (!empty($_POST['par1']) && !empty($_POST['par2'])) {
        $date1 = DateTime::createFromFormat('d-m-Y', $_POST['par1']);
        $date2 = DateTime::createFromFormat('d-m-Y', $_POST['par2']);
        
        if ($date1 && $date2) {
            $par1 = $date1->format('Y');
            $par2 = $date2->format('Y');
            $queryExecuted = true;
            
            // Build secure WHERE clause
            if ($statusBayar == "lunas") {
                $where .= " AND YEAR(a.tglmasehi) >= ? AND YEAR(a.tglmasehi) <= ? 
                           GROUP BY a.id, YEAR(a.tglmasehi)
                           HAVING SUM(a.bayar) >= SUM(a.kewajiban)";
            } else if ($statusBayar == "bayar") {
                $where .= " AND YEAR(a.tglmasehi) >= ? AND YEAR(a.tglmasehi) <= ? 
                           GROUP BY a.id, YEAR(a.tglmasehi)
                           HAVING SUM(a.bayar) > 0 AND SUM(a.bayar) < SUM(a.kewajiban)";
            } else {
                $where .= " AND YEAR(a.tglmasehi) >= ? AND YEAR(a.tglmasehi) <= ? 
                           GROUP BY a.id, YEAR(a.tglmasehi) 
                           HAVING SUM(a.bayar) = 0";
            }
        }
    }
}

// Function to get table display name
function getTableDisplayName($table) {
    $names = [
        'bulanan' => 'Syahriah',
        'iktibar' => 'Ikhtibar', 
        'kitab' => 'Kitab',
        'imda1' => 'Imda-I',
        'imda2' => 'Imda-II',
        'imda3' => 'Imda-III'
    ];
    return isset($names[$table]) ? $names[$table] : $table;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Pembayaran</title>
    
    <!-- Enhanced CSS with modern design -->
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --light-bg: #ecf0f1;
            --white: #ffffff;
            --shadow: 0 2px 10px rgba(0,0,0,0.1);
            --border-radius: 8px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
            color: var(--white);
            padding: 20px 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

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

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

        .btn-primary:hover, .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }

        .form-section {
            padding: 30px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }

        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: end;
            margin-bottom: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            min-width: 120px;
        }

        .form-group label {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 5px;
            font-size: 12px;
            text-transform: uppercase;
        }

        .form-control {
            padding: 10px 12px;
            border: 2px solid #e1e8ed;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }

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

        .datepicker-input {
            width: 130px;
        }

        .datepicker-btn {
            margin-left: 5px;
            padding: 8px;
            background: var(--secondary-color);
            border: none;
            border-radius: 5px;
            cursor: pointer;
            color: white;
        }

        .export-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .export-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 15px;
            background: var(--white);
            border: 2px solid #e1e8ed;
            border-radius: 5px;
            text-decoration: none;
            color: var(--primary-color);
            transition: all 0.3s ease;
        }

        .export-btn:hover {
            border-color: var(--secondary-color);
            color: var(--secondary-color);
            transform: translateY(-2px);
        }

        .table-section {
            padding: 30px;
        }

        .table-responsive {
            overflow-x: auto;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: var(--white);
            margin: 0;
        }

        .data-table thead {
            background: linear-gradient(45deg, var(--primary-color), #34495e);
            color: var(--white);
        }

        .data-table th {
            padding: 15px 12px;
            text-align: center;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            padding: 12px;
            border-bottom: 1px solid #e9ecef;
            font-size: 14px;
        }

        .data-table tbody tr:hover {
            background: #f8f9fa;
        }

        .data-table tbody tr:nth-child(even) {
            background: #fdfdfd;
        }

        .total-row {
            background: linear-gradient(45deg, #2c3e50, #34495e) !important;
            color: var(--white);
            font-weight: bold;
        }

        .total-row td {
            border-bottom: none;
        }

        .text-right {
            text-align: right;
        }

        .text-center {
            text-align: center;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #666;
            font-style: italic;
        }

        .datepicker {
            position: absolute;
            z-index: 1000;
            background: var(--white);
            border: 2px solid #e1e8ed;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
        }

        /* Responsive design */
        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
            }
            
            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
            
            .export-actions {
                justify-content: center;
            }
        }

        /* Loading animation */
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--secondary-color);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>?? Laporan Pembayaran <?php echo $dataTable ? getTableDisplayName($dataTable) : ''; ?></h1>
            <div class="header-actions">
                <button type="button" class="btn btn-primary" onclick="toggleCollapse()">
                    <span id="collapse-icon">?</span>
                </button>
            </div>
        </div>

        <!-- Form Section -->
        <div class="form-section" id="form-section">
            <form role="form" method="POST" id="reportForm">
                <div class="form-row">
                    <div class="form-group">
                        <label>Jenis Pembayaran</label>
                        <select class="form-control" name="dataTable" id="dataTable" required>
                            <option value="">Pilih Jenis</option>
                            <option value="bulanan" <?php echo ($dataTable == 'bulanan') ? 'selected' : ''; ?>>Syahriah</option>
                            <option value="iktibar" <?php echo ($dataTable == 'iktibar') ? 'selected' : ''; ?>>Ikhtibar</option>
                            <option value="kitab" <?php echo ($dataTable == 'kitab') ? 'selected' : ''; ?>>Kitab</option>
                            <option value="imda1" <?php echo ($dataTable == 'imda1') ? 'selected' : ''; ?>>Imda-I</option>
                            <option value="imda2" <?php echo ($dataTable == 'imda2') ? 'selected' : ''; ?>>Imda-II</option>
                            <option value="imda3" <?php echo ($dataTable == 'imda3') ? 'selected' : ''; ?>>Imda-III</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Status Bayar</label>
                        <select class="form-control" name="statusBayar" id="statusBayar" required>
                            <option value="">Pilih Status</option>
                            <option value="lunas" <?php echo ($statusBayar == 'lunas') ? 'selected' : ''; ?>>? Lunas</option>
                            <option value="bayar" <?php echo ($statusBayar == 'bayar') ? 'selected' : ''; ?>>?? Bayar Sebagian</option>
                            <option value="tidak" <?php echo ($statusBayar == 'tidak') ? 'selected' : ''; ?>>? Belum Bayar</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Dari Tanggal</label>
                        <div class="datepicker-wrapper">
                            <input type="text" name="par1" id="par1" class="form-control datepicker-input" 
                                   value="<?php echo isset($_POST['par1']) ? htmlspecialchars($_POST['par1']) : (sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2]); ?>" 
                                   placeholder="dd-mm-yyyy" required readonly>
                            <button type="button" class="datepicker-btn" onclick="pickADate1()">??</button>
                        </div>
                        <div id="calendar-popup1" class="datepicker" style="display:none;"></div>
                    </div>

                    <div class="form-group">
                        <label>Sampai Tanggal</label>
                        <div class="datepicker-wrapper">
                            <input type="text" name="par2" id="par2" class="form-control datepicker-input" 
                                   value="<?php echo isset($_POST['par2']) ? htmlspecialchars($_POST['par2']) : (sprintf('%02d', $hijri[1]) . '-' . $calendar->monthName($hijri[0]) . '-' . $hijri[2]); ?>" 
                                   placeholder="dd-mm-yyyy" required readonly>
                            <button type="button" class="datepicker-btn" onclick="pickADate2()">??</button>
                        </div>
                        <div id="calendar-popup2" class="datepicker" style="display:none;"></div>
                    </div>

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">
                            ?? Cari Data
                        </button>
                    </div>
                </div>

                <?php if ($queryExecuted): ?>
                <div class="export-actions">
                    <?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_nonsyahriah_murid.php" target="_blank" class="export-btn">
                        ?? Download Excel
                    </a>
                    <a href="pdf/lap_bayar_kewajiban_muridpdf.php" target="_blank" class="export-btn">
                        ?? Download PDF
                    </a>
                </div>
                <?php endif; ?>
            </form>
        </div>

        <!-- Loading indicator -->
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>Memproses data...</p>
        </div>

        <!-- Table Section -->
        <div class="table-section">
            <div class="table-responsive">
                <table class="data-table" id="sortTable">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>ID</th>
                            <th>NIM</th>
                            <th>Tanggal</th>
                            <th>Nama</th>
                            <th>Kewajiban</th>
                            <th>Bayar</th>
                            <th>Sisa</th>
                            <th>Kelas</th>
                            <th>Keterangan</th>
                            <th>User</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($queryExecuted && !empty($dataTable)) {
                            // Use prepared statement for security
                            $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, 
                                       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
                                       FROM `$dataTable` a 
                                       LEFT JOIN registrasi b ON a.id = b.id 
                                       $where";
                            
                            $stmt = mysqli_prepare($koneksi, $queryba);
                            $_SESSION['bayar_nonsyahriah']['kode']['sqlbyr']=$queryba;
                            if ($stmt) {
                                mysqli_stmt_bind_param($stmt, "ss", $par1, $par2);
                                mysqli_stmt_execute($stmt);
                                $result = mysqli_stmt_get_result($stmt);
                                
                                $_SESSION['bayar_nonsyahriah']['kode']['sqlbyr'] = $queryba;

                                if ($result && mysqli_num_rows($result) > 0) {
                                    $t_kwajiban = 0;
                                    $t_bayar = 0;
                                    $t_sisa = 0;
                                    $no = 0;

                                    while ($barisD = mysqli_fetch_assoc($result)) {
                                        $t_kwajiban += $barisD['kewajiban'];
                                        $t_bayar += $barisD['bayar'];
                                        $t_sisa += $barisD['sisa'];
                                        $no++;
                                        
                                        // Determine row color based on payment status
                                        $rowClass = '';
                                        if ($barisD['sisa'] < 0) $rowClass = 'style="background-color: #d4edda;"'; // Paid
                                        else if ($barisD['bayar'] > 0) $rowClass = 'style="background-color: #fff3cd;"'; // Partial
                                        else $rowClass = 'style="background-color: #f8d7da;"'; // Unpaid
                                        ?>
                                        <tr <?php echo $rowClass; ?>>
                                            <td class="text-center"><?php echo $no; ?></td>
                                            <td><?php echo htmlspecialchars($barisD['id']); ?></td>
                                            <td><?php echo htmlspecialchars($barisD['nim']); ?></td>
                                            <td><?php echo date('d-m-Y', strtotime($barisD['tglmasehi'])); ?></td>
                                            <td><?php echo htmlspecialchars($barisD['nama']); ?></td>
                                            <td class="text-right">Rp <?php echo number_format($barisD['kewajiban'], 0, ',', '.'); ?></td>
                                            <td class="text-right">Rp <?php echo number_format($barisD['bayar'], 0, ',', '.'); ?></td>
                                            <td class="text-right">Rp <?php echo number_format($barisD['sisa'], 0, ',', '.'); ?></td>
                                            <td class="text-center"><?php echo htmlspecialchars($barisD['no_kls']); ?></td>
                                            <td><?php echo htmlspecialchars($barisD['keterangan']); ?></td>
                                            <td><?php echo htmlspecialchars($barisD['username']); ?></td>
                                        </tr>
                                        <?php
                                    }
                                    ?>
                                    <tr class="total-row">
                                        <td colspan="5" class="text-center"><strong>?? TOTAL KESELURUHAN</strong></td>
                                        <td class="text-right"><strong>Rp <?php echo number_format($t_kwajiban, 0, ',', '.'); ?></strong></td>
                                        <td class="text-right"><strong>Rp <?php echo number_format($t_bayar, 0, ',', '.'); ?></strong></td>
                                        <td class="text-right"><strong>Rp <?php echo number_format($t_sisa, 0, ',', '.'); ?></strong></td>
                                        <td colspan="3"></td>
                                    </tr>
                                    <?php
                                } else {
                                    echo '<tr><td colspan="11" class="no-data">?? Tidak ada data yang ditemukan untuk kriteria yang dipilih.</td></tr>';
                                }
                                mysqli_stmt_close($stmt);
                            } else {
                                echo '<tr><td colspan="11" class="no-data">? Error dalam memproses query: ' . mysqli_error($koneksi) . '</td></tr>';
                            }
                        } else {
                            echo '<tr><td colspan="11" class="no-data">?? Silakan pilih kriteria pencarian dan klik "Cari Data" untuk menampilkan laporan.</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- External CSS and JS -->
    <link rel="stylesheet" href="calendar.css"/>
    <link rel="stylesheet" type="text/css" href="./assets/jquery.dataTables.css">
    
    <script type="text/javascript" src="hijri-date.js"></script>
    <script type="text/javascript" src="calendar.js"></script>
    <script type="text/javascript" charset="utf8" src="./assets/jquery.dataTables.js"></script>

    <script type="text/javascript">
        // Enhanced datepicker functionality
        var pickedTxt1 = document.getElementById('par1'),
            datepicker1 = new Calendar(true, 0, false, true);
        document.getElementById('calendar-popup1').appendChild(datepicker1.getElement());
        
        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;
            datepicker1.hide();
        };

        function pickADate1() {
            datepicker1.show();
            addClickOutsideListener(datepicker1, 'calendar-popup1');
        }

        var pickedTxt2 = document.getElementById('par2'),
            datepicker2 = new Calendar(true, 0, false, true);
        document.getElementById('calendar-popup2').appendChild(datepicker2.getElement());
        
        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;
            datepicker2.hide();
        };

        function pickADate2() {
            datepicker2.show();
            addClickOutsideListener(datepicker2, 'calendar-popup2');
        }

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

        // Toggle collapse functionality
        function toggleCollapse() {
            var formSection = document.getElementById('form-section');
            var icon = document.getElementById('collapse-icon');
            
            if (formSection.style.display === 'none') {
                formSection.style.display = 'block';
                icon.textContent = '?';
            } else {
                formSection.style.display = 'none';
                icon.textContent = '?';
            }
        }

        // Enhanced form submission with loading
        document.getElementById('reportForm').addEventListener('submit', function(e) {
            var loading = document.getElementById('loading');
            loading.style.display = 'block';
            
            // Validate form
            var dataTable = document.getElementById('dataTable').value;
            var statusBayar = document.getElementById('statusBayar').value;
            var par1 = document.getElementById('par1').value;
            var par2 = document.getElementById('par2').value;
            
            if (!dataTable || !statusBayar || !par1 || !par2) {
                e.preventDefault();
                loading.style.display = 'none';
                alert('?? Harap lengkapi semua field yang diperlukan!');
                return false;
            }
            
            // Date validation
            var date1 = new Date(par1.split('-').reverse().join('-'));
            var date2 = new Date(par2.split('-').reverse().join('-'));
            
            if (date1 > date2) {
                e.preventDefault();
                loading.style.display = 'none';
                alert('?? Tanggal "Dari" tidak boleh lebih besar dari tanggal "Sampai"!');
                return false;
            }
        });

        // Initialize DataTable with enhanced options
        $(document).ready(function() {
            $('#sortTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Indonesian.json"
                },
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Semua"]],
                "dom": 'Bfrtip',
                "responsive": true,
                "order": [[ 0, "asc" ]],
                "columnDefs": [
                    { "orderable": false, "targets": [9, 10] }
                ]
            });
        });

        // Auto-hide loading on page load
        window.addEventListener('load', function() {
            document.getElementById('loading').style.display = 'none';
        });
    </script>
</body>
</html>