<?php

/**
 *
 * Copyright (C) 2007,2008  Arie Nugraha (dicarve@yahoo.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/* Fines Report */

// key to authenticate
define('INDEX_AUTH', '1');

// main system configuration
require '../../../../sysconfig.inc.php';
// IP based access limitation
require LIB . 'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-reporting');
// start the session
require SB . 'admin/default/session.inc.php';
require SB . 'admin/default/session_check.inc.php';

// ========== TAMBAHAN MULTI-LIBRARY ==========
$current_library_id = isset($_SESSION['library_id']) ? (int)$_SESSION['library_id'] : 1;
$is_superadmin = isset($_SESSION['uid']) && $_SESSION['uid'] == 1;
// ========== AKHIR TAMBAHAN ==========

// privileges checking
$can_read = utility::havePrivilege('reporting', 'r');
$can_write = utility::havePrivilege('reporting', 'w');

if (!$can_read) {
    die('<div class="errorBox">' . __('You don\'t have enough privileges to access this area!') . '</div>');
}

require SIMBIO . 'simbio_GUI/form_maker/simbio_form_element.inc.php';
require SIMBIO . 'simbio_UTILS/simbio_date.inc.php';

// months array
$months['01'] = __('Jan');
$months['02'] = __('Feb');
$months['03'] = __('Mar');
$months['04'] = __('Apr');
$months['05'] = __('May');
$months['06'] = __('Jun');
$months['07'] = __('Jul');
$months['08'] = __('Aug');
$months['09'] = __('Sep');
$months['10'] = __('Oct');
$months['11'] = __('Nov');
$months['12'] = __('Dec');

$page_title = 'Fines Report';
$reportView = false;
if (isset($_GET['reportView'])) {
    $reportView = true;
}

// ========== TAMBAHAN: Informasi Library di Header ==========
$library_info = '';
if (!$is_superadmin) {
    $lib_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . $current_library_id);
    if ($lib_q->num_rows > 0) {
        $lib_d = $lib_q->fetch_assoc();
        $library_info = ' - ' . $lib_d['library_name'];
    }
}
// ========== AKHIR TAMBAHAN ==========

if (!$reportView) {
?>
    <div class="menuBox">
        <div class="menuBoxInner">
            <!-- filter -->
            <div class="per_title">
                <h2><?php echo __('Fines Report'); ?></h2>
            </div>
            <div class="infoBox">
                <?php echo __('Report Filter'); ?>
                <?php if (!$is_superadmin) { echo '<strong> - ' . $library_info . '</strong>'; } ?>
            </div>
            <div class="sub_section">
                <div>&nbsp;</div>
                <form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>" target="reportView">
                    <div id="filterForm">
                        <!-- ========== TAMBAHAN: Filter Library untuk Superadmin ========== -->
                        <?php if ($is_superadmin) { ?>
                        <div class="form-group divRow">
                            <label><?php echo __('Library'); ?></label>
                            <?php
                            $lib_q = $dbs->query('SELECT library_id, library_name FROM mst_library ORDER BY library_name');
                            $lib_options = array();
                            $lib_options[] = array('0', __('ALL Libraries'));
                            while ($lib_d = $lib_q->fetch_row()) {
                                $lib_options[] = array($lib_d[0], $lib_d[1]);
                            }
                            echo simbio_form_element::selectList('library_id', $lib_options, '', 'class="form-control col-2"');
                            ?>
                        </div>
                        <?php } ?>
                        <!-- ========== AKHIR TAMBAHAN ========== -->
                        <div class="form-group divRow">
                            <label><?php echo __('Year'); ?></label>
                            <?php
                            $current_year = date('Y');
                            $year_options = array();
                            $year = $dbs->query("SELECT DISTINCT year(loan_date) AS y FROM loan ORDER BY y DESC");
                            if ($year->num_rows > 0) {
                                while ($y = $year->fetch_row()) {
                                    $year_options[] = array($y[0], $y[0]);
                                }
                            } else {
                                $year_options[] = array($current_year, $current_year);
                            }
                            echo simbio_form_element::selectList('year', $year_options, $current_year, 'class="form-control col-1"');
                            ?>
                        </div>
                        <div class="form-group divRow">
                            <label><?php echo __('Month'); ?></label>
                            <?php
                            $current_month = date('m');
                            $month_options = array();
                            foreach ($months as $idx => $month) {
                                $month_options[] = array($idx, $month);
                            }
                            echo simbio_form_element::selectList('month', $month_options, $current_month, 'class="form-control col-1"');
                            ?>
                        </div>
                        <!-- ========== TAMBAHAN: Filter Status ========== -->
                        <div class="form-group divRow">
                            <label><?php echo __('Status'); ?></label>
                            <select name="status_filter" class="form-control col-2">
                                <option value="ALL"><?php echo __('ALL'); ?></option>
                                <option value="unpaid"><?php echo __('Unpaid'); ?></option>
                                <option value="partial"><?php echo __('Partial'); ?></option>
                                <option value="paid"><?php echo __('Paid'); ?></option>
                                <option value="waived"><?php echo __('Waived'); ?></option>
                            </select>
                        </div>
                        <!-- ========== AKHIR TAMBAHAN ========== -->
                    </div>
                    <input type="button" name="moreFilter" class="btn btn-default" value="<?php echo __('Show More Filter Options'); ?>" />
                    <input type="submit" name="applyFilter" class="btn btn-primary" value="<?php echo __('Apply Filter'); ?>" />
                    <input type="hidden" name="reportView" value="true" />
                </form>
            </div>
        </div>
    </div>
    <!-- filter end -->
    <iframe name="reportView" id="reportView" src="<?php echo $_SERVER['PHP_SELF'] . '?reportView=true'; ?>" frameborder="0" style="width: 100%; height: 500px;"></iframe>
<?php
} else {
    ob_start();
    $fines_data = array();
    // year
    $selected_year = date('Y');
    if (isset($_GET['year']) and !empty($_GET['year'])) {
        $selected_year = (int)$dbs->real_escape_string($_GET['year']);
    }

    // month
    $selected_month = date('m');
    if (isset($_GET['month']) and !empty($_GET['month'])) {
        $allowed_month = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
        if (in_array($_GET['month'], $allowed_month)) {
            $selected_month = (int)$dbs->real_escape_string($_GET['month']);
        } else {
            $selected_month = 1;
        }
    }

    // ========== FILTER STATUS ==========
    $status_filter = '';
    if (isset($_GET['status_filter']) && $_GET['status_filter'] != 'ALL') {
        $status_filter = " AND status = '" . $dbs->real_escape_string($_GET['status_filter']) . "'";
    }
    // ========== AKHIR FILTER STATUS ==========

    // ========== PERBAIKAN: Filter Library ==========
    $filter_library = '';
    
    // Filter Library untuk Superadmin
    if ($is_superadmin && isset($_GET['library_id']) && $_GET['library_id'] > 0) {
        $filter_library = " AND library_id = " . (int)$_GET['library_id'];
    } elseif (!$is_superadmin) {
        $filter_library = " AND library_id = " . $current_library_id;
    }
    // ========== AKHIR PERBAIKAN ==========

    // ========== PERBAIKAN: Query Kalender ==========
    $sql_str = "SELECT DAY(fines_date) AS `mdate`, SUM(debet - credit - discount_amount) AS `dtotal` 
                FROM `fines` 
                WHERE YEAR(fines_date) = $selected_year 
                AND MONTH(fines_date) = $selected_month 
                $filter_library $status_filter
                GROUP BY DAY(fines_date)";
    // ========== AKHIR PERBAIKAN ==========
    
    // debug box
    if (isDev() !== false) {
        debugBox(content: function () use ($sql_str) {
            debug($sql_str);
        });
    }
    $_fines_q = $dbs->query($sql_str);
    while ($_fines_d = $_fines_q->fetch_row()) {
        $date = (int)$_fines_d[0];
        $link_params = 'reportView=true&singleDate=true&finesDate=' . $selected_year . '-' . str_pad($selected_month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($date, 2, '0', STR_PAD_LEFT);
        if (!$is_superadmin) {
            $link_params .= '&library_id=' . $current_library_id;
        } elseif ($is_superadmin && isset($_GET['library_id']) && $_GET['library_id'] > 0) {
            $link_params .= '&library_id=' . (int)$_GET['library_id'];
        }
        if (isset($_GET['status_filter']) && $_GET['status_filter'] != 'ALL') {
            $link_params .= '&status=' . $_GET['status_filter'];
        }
        $fines_data[$date] = '<div class="data"><a href="' . AWB . 'modules/reporting/customs/member_fines_list.php?' . $link_params . '" class="notAJAX openPopUp" width="800" height="600" title="' . __('Member Fines List') . '">' . currency($_fines_d[1] ?: '0') . '</a></div>';
    }

    // ========== TAMBAHAN: Informasi Library ==========
    $library_info = '';
    if ($is_superadmin && isset($_GET['library_id']) && $_GET['library_id'] > 0) {
        $lib_name_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . (int)$_GET['library_id']);
        if ($lib_name_q->num_rows > 0) {
            $lib_name_d = $lib_name_q->fetch_assoc();
            $library_info = ' - ' . $lib_name_d['library_name'];
        }
    } elseif (!$is_superadmin) {
        $lib_q = $dbs->query("SELECT library_name FROM mst_library WHERE library_id = " . $current_library_id);
        if ($lib_q->num_rows > 0) {
            $lib_d = $lib_q->fetch_assoc();
            $library_info = ' - ' . $lib_d['library_name'];
        }
    }
    // ========== AKHIR TAMBAHAN ==========

    // generate calendar
    $output = simbio_date::generateCalendar($selected_year, str_pad($selected_month, 2, '0', STR_PAD_LEFT), $fines_data);

    // print out
    echo '<div class="mb-2">' . __('Fines count report for') . ' <strong>' . $months[str_pad($selected_month, 2, '0', STR_PAD_LEFT)] . ', ' . $selected_year . '</strong>' . $library_info . ' <a class="s-btn btn btn-default printReport" onclick="window.print()" href="#">' . __('Print Current Page') . '</a></div>' . "\n";
    echo $output;

    // ================================================================
    // TAMBAHAN: TABEL RINGKASAN DENDA
    // ================================================================
    
    // ========== PERBAIKAN: Query untuk tabel ringkasan ==========
    $sql_summary = "SELECT 
                        COUNT(*) as total_fines,
                        SUM(debet) as total_debet,
                        SUM(credit) as total_credit,
                        SUM(discount_amount) as total_discount,
                        SUM(debet - credit - discount_amount) as total_remaining,
                        SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid_count,
                        SUM(CASE WHEN status = 'partial' THEN 1 ELSE 0 END) as partial_count,
                        SUM(CASE WHEN status = 'unpaid' THEN 1 ELSE 0 END) as unpaid_count,
                        SUM(CASE WHEN status = 'waived' THEN 1 ELSE 0 END) as waived_count
                    FROM fines 
                    WHERE YEAR(fines_date) = $selected_year 
                    AND MONTH(fines_date) = $selected_month 
                    $filter_library $status_filter";
    
    $_summary_q = $dbs->query($sql_summary);
    $summary_data = $_summary_q->fetch_assoc();
    
    // ========== Query untuk daftar per tanggal ==========
    $sql_list = "SELECT 
                        fines_date,
                        COUNT(*) as total,
                        SUM(debet) as debet,
                        SUM(credit) as credit,
                        SUM(discount_amount) as discount,
                        SUM(debet - credit - discount_amount) as remaining
                    FROM fines 
                    WHERE YEAR(fines_date) = $selected_year 
                    AND MONTH(fines_date) = $selected_month 
                    $filter_library $status_filter
                    GROUP BY fines_date
                    ORDER BY fines_date DESC";
    
    $_list_q = $dbs->query($sql_list);
    // ================================================================
    
    // ========== TAMPILKAN TABEL RINGKASAN ==========
    $total_fines = $summary_data['total_fines'] ?? 0;
    $total_debet = $summary_data['total_debet'] ?? 0;
    $total_credit = $summary_data['total_credit'] ?? 0;
    $total_discount = $summary_data['total_discount'] ?? 0;
    $total_remaining = $summary_data['total_remaining'] ?? 0;
    $paid_count = $summary_data['paid_count'] ?? 0;
    $partial_count = $summary_data['partial_count'] ?? 0;
    $unpaid_count = $summary_data['unpaid_count'] ?? 0;
    $waived_count = $summary_data['waived_count'] ?? 0;
    
    echo '<div class="mt-4">';
    echo '<h4>' . __('Fines Summary') . '</h4>';
    echo '<table class="s-table table table-bordered table-sm" style="width: 100%;">';
    echo '<thead class="dataListHeader">';
    echo '<tr>';
    echo '<th>' . __('Total Fines') . '</th>';
    echo '<th>' . __('Total Debet') . '</th>';
    echo '<th>' . __('Total Credit') . '</th>';
    echo '<th>' . __('Total Discount') . '</th>';
    echo '<th>' . __('Total Remaining') . '</th>';
    echo '<th>' . __('Paid') . '</th>';
    echo '<th>' . __('Partial') . '</th>';
    echo '<th>' . __('Unpaid') . '</th>';
    echo '<th>' . __('Waived') . '</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    echo '<tr>';
    echo '<td><strong>' . $total_fines . '</strong></td>';
    echo '<td>' . currency($total_debet) . '</td>';
    echo '<td>' . currency($total_credit) . '</td>';
    echo '<td>' . currency($total_discount) . '</td>';
    $remaining_class = ($total_remaining > 0) ? 'text-danger' : 'text-success';
    echo '<td><strong class="' . $remaining_class . '">' . currency($total_remaining) . '</strong></td>';
    echo '<td>' . $paid_count . '</td>';
    echo '<td>' . $partial_count . '</td>';
    echo '<td>' . $unpaid_count . '</td>';
    echo '<td>' . $waived_count . '</td>';
    echo '</tr>';
    echo '</tbody>';
    echo '</table>';
    echo '</div>';
    
    // ========== TAMPILKAN TABEL DETAIL PER TANGGAL ==========
    if ($_list_q->num_rows > 0) {
        echo '<div class="mt-4">';
        echo '<h4>' . __('Daily Fines Detail') . '</h4>';
        echo '<table class="s-table table table-bordered table-sm" style="width: 100%;">';
        echo '<thead class="dataListHeader">';
        echo '<tr>';
        echo '<th>' . __('Date') . '</th>';
        echo '<th>' . __('Total Items') . '</th>';
        echo '<th>' . __('Debet') . '</th>';
        echo '<th>' . __('Credit') . '</th>';
        echo '<th>' . __('Discount') . '</th>';
        echo '<th>' . __('Remaining') . '</th>';
        echo '<th>' . __('Action') . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        while ($row = $_list_q->fetch_assoc()) {
            $remaining = $row['remaining'] ?? 0;
            $row_class = ($remaining > 0) ? 'text-danger' : 'text-success';
            $link_params_detail = 'reportView=true&singleDate=true&finesDate=' . $row['fines_date'];
            if (!$is_superadmin) {
                $link_params_detail .= '&library_id=' . $current_library_id;
            } elseif ($is_superadmin && isset($_GET['library_id']) && $_GET['library_id'] > 0) {
                $link_params_detail .= '&library_id=' . (int)$_GET['library_id'];
            }
            if (isset($_GET['status_filter']) && $_GET['status_filter'] != 'ALL') {
                $link_params_detail .= '&status=' . $_GET['status_filter'];
            }
            echo '<tr>';
            echo '<td>' . $row['fines_date'] . '</td>';
            echo '<td>' . $row['total'] . '</td>';
            echo '<td>' . currency($row['debet'] ?? 0) . '</td>';
            echo '<td>' . currency($row['credit'] ?? 0) . '</td>';
            echo '<td>' . currency($row['discount'] ?? 0) . '</td>';
            echo '<td class="' . $row_class . '"><strong>' . currency($remaining) . '</strong></td>';
            echo '<td><a href="' . AWB . 'modules/reporting/customs/member_fines_list.php?' . $link_params_detail . '" class="btn btn-default btn-sm openPopUp" width="800" height="600" title="' . __('View Details') . '">' . __('View') . '</a></td>';
            echo '</tr>';
        }
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
    } else {
        echo '<div class="infoBox mt-4" style="background: #f0f8ff; padding: 15px; border: 1px solid #b0d4f0; border-radius: 4px;">';
        echo '<strong>' . __('ℹ️ No fines data found') . '</strong><br>';
        echo __('There are no fines recorded for the selected period') . ' (' . $months[str_pad($selected_month, 2, '0', STR_PAD_LEFT)] . ', ' . $selected_year . ').';
        echo '</div>';
    }
    // ========== AKHIR TABEL RINGKASAN ==========

    $content = ob_get_clean();
    // include the page template
    require SB . '/admin/' . $sysconf['admin_template']['dir'] . '/notemplate_page_tpl.php';
}