<?php
/**
 * Popup Pembayaran Denda
 * File: pop_fines_payment.php
 * Fungsi: Popup untuk pembayaran denda
 */

// key to authenticate
if (!defined('INDEX_AUTH')) {
    define('INDEX_AUTH', '1');
}
// key to get full database access
define('DB_ACCESS', 'fa');

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

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

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

if (!$can_read || !$can_write) {
    die('<div class="errorBox">' . __('You are not authorized to access this section') . '</div>');
}

// Get fines_id from URL
$fines_id = isset($_GET['fines_id']) ? (int)$_GET['fines_id'] : 0;
if ($fines_id <= 0) {
    die('<div class="errorBox">' . __('Invalid fines ID') . '</div>');
}

// Get fines data
$query = $dbs->query("SELECT f.*, m.member_name, m.member_id 
                      FROM fines f
                      LEFT JOIN member m ON f.member_id = m.member_id
                      WHERE f.fines_id = $fines_id AND f.library_id = $current_library_id");

if ($query->num_rows == 0) {
    die('<div class="errorBox">' . __('Fines data not found or you do not have permission to access it.') . '</div>');
}

$fine = $query->fetch_assoc();

// Calculate remaining balance
$remaining = $fine['debet'] - $fine['credit'] - $fine['discount_amount'];
$remaining = max(0, $remaining); // prevent negative value

// Get staff info for discount_by
$staff_query = $dbs->query("SELECT realname, username FROM user WHERE user_id = " . (int)$_SESSION['uid']);
$staff_data = $staff_query->fetch_assoc();
$staff_name = $staff_data['realname'] ?? $staff_data['username'] ?? $logged_user;

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title><?php echo __('Fines Payment'); ?></title>
    <link rel="stylesheet" href="<?php echo SWB; ?>admin/<?php echo $sysconf['admin_template']['dir']; ?>/<?php echo $sysconf['admin_template']['theme']; ?>/template.css">
    <style>
        body { padding: 20px; font-family: Arial, sans-serif; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: inline-block; width: 150px; font-weight: bold; }
        .form-group .value { display: inline-block; }
        .form-control { padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 250px; }
        .form-control.textarea { width: 300px; height: 60px; }
        .btn { padding: 8px 20px; border: none; border-radius: 4px; cursor: pointer; }
        .btn-primary { background: #004db6; color: #fff; }
        .btn-danger { background: #e74c3c; color: #fff; }
        .btn-success { background: #27ae60; color: #fff; }
        .btn-warning { background: #f39c12; color: #fff; }
        .btn-default { background: #95a5a6; color: #fff; }
        .info-box { background: #f0f8ff; padding: 10px; border: 1px solid #b0d4f0; border-radius: 4px; margin-bottom: 20px; }
        .error-box { background: #ffe6e6; padding: 10px; border: 1px solid #ff9999; border-radius: 4px; margin-bottom: 20px; color: #cc0000; }
        .success-box { background: #e6ffe6; padding: 10px; border: 1px solid #99cc99; border-radius: 4px; margin-bottom: 20px; color: #008800; }
        .row { margin: 5px 0; }
        .col-6 { display: inline-block; width: 48%; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        table { width: 100%; border-collapse: collapse; }
        td { padding: 8px; border-bottom: 1px solid #eee; }
        .total-amount { font-size: 24px; font-weight: bold; color: #004db6; }
        .status-unpaid { color: #e74c3c; font-weight: bold; }
        .status-partial { color: #f39c12; font-weight: bold; }
        .status-paid { color: #27ae60; font-weight: bold; }
        .status-waived { color: #3498db; font-weight: bold; }
    </style>
</head>
<body>
    <h2><?php echo __('Fines Payment'); ?></h2>
    
    <div class="info-box">
        <strong><?php echo __('Member'); ?>:</strong> <?php echo $fine['member_name'] . ' (' . $fine['member_id'] . ')' ?><br>
        <strong><?php echo __('Description'); ?>:</strong> <?php echo $fine['description'] ?><br>
        <strong><?php echo __('Status'); ?>:</strong> 
        <span class="status-<?php echo $fine['status'] ?? 'unpaid'; ?>">
            <?php echo strtoupper($fine['status'] ?? 'UNPAID'); ?>
        </span>
    </div>

    <form id="paymentForm" method="post" action="<?php echo MWB; ?>circulation/circulation_action.php">
        <input type="hidden" name="action" value="fines_payment">
        <input type="hidden" name="fines_id" value="<?php echo $fines_id; ?>">
        <input type="hidden" name="member_id" value="<?php echo $fine['member_id']; ?>">
        <input type="hidden" name="staff_name" value="<?php echo $staff_name; ?>">

        <table>
            <tr>
                <td width="30%"><strong><?php echo __('Total Debet'); ?></strong></td>
                <td width="70%"><?php echo currency($fine['debet']); ?></td>
            </tr>
            <tr>
                <td><strong><?php echo __('Total Credit (Paid)'); ?></strong></td>
                <td><?php echo currency($fine['credit']); ?></td>
            </tr>
            <tr>
                <td><strong><?php echo __('Discount Given'); ?></strong></td>
                <td><?php echo currency($fine['discount_amount'] ?? 0); ?></td>
            </tr>
            <tr>
                <td><strong><?php echo __('Remaining Balance'); ?></strong></td>
                <td><span class="total-amount"><?php echo currency($remaining); ?></span></td>
            </tr>
        </table>

        <hr>

        <div class="form-group">
            <label><?php echo __('Discount Amount'); ?> (Rp)</label>
            <input type="number" name="discount_amount" id="discount_amount" 
                   class="form-control" min="0" max="<?php echo $remaining; ?>" 
                   value="0" onchange="updateRemaining()">
            <small class="text-muted"><?php echo __('Enter discount amount (max: ' . currency($remaining) . ')'); ?></small>
        </div>

        <div class="form-group">
            <label><?php echo __('Discount Reason'); ?></label>
            <input type="text" name="discount_reason" id="discount_reason" 
                   class="form-control" placeholder="<?php echo __('e.g. Student hardship, special request, etc.'); ?>">
        </div>

        <div class="form-group">
            <label><?php echo __('Payment Amount'); ?> (Rp)</label>
            <input type="number" name="payment_amount" id="payment_amount" 
                   class="form-control" min="0" value="0" onchange="updateRemaining()">
            <small class="text-muted"><?php echo __('Enter amount paid by member'); ?></small>
        </div>

        <div class="form-group">
            <label><?php echo __('Notes'); ?></label>
            <textarea name="notes" id="notes" class="form-control textarea" 
                      placeholder="<?php echo __('Additional notes...'); ?>"></textarea>
        </div>

        <div class="form-group">
            <label><?php echo __('Payment Status'); ?></label>
            <select name="status" id="status" class="form-control">
                <option value="partial"><?php echo __('Partial (Still has remaining balance)'); ?></option>
                <option value="paid"><?php echo __('Paid (Fully paid)'); ?></option>
                <option value="waived"><?php echo __('Waived (Fully waived)'); ?></option>
            </select>
            <small class="text-muted"><?php echo __('Select status after payment/discount'); ?></small>
        </div>

        <div id="remaining_info" class="info-box" style="margin-top: 10px;">
            <strong><?php echo __('New Remaining Balance'); ?>:</strong> 
            <span id="new_remaining" class="total-amount"><?php echo currency($remaining); ?></span>
        </div>

        <div class="text-center" style="margin-top: 20px;">
            <button type="button" class="btn btn-danger" onclick="window.close()"><?php echo __('Cancel'); ?></button>
            <button type="submit" class="btn btn-success" onclick="return validateForm()"><?php echo __('Save Payment'); ?></button>
        </div>
    </form>

    <script>
        function updateRemaining() {
            var originalRemaining = <?php echo $remaining; ?>;
            var discount = parseInt(document.getElementById('discount_amount').value) || 0;
            var payment = parseInt(document.getElementById('payment_amount').value) || 0;
            
            var newRemaining = originalRemaining - discount - payment;
            newRemaining = Math.max(0, newRemaining);
            
            document.getElementById('new_remaining').textContent = formatCurrency(newRemaining);
            
            // Auto update status based on new remaining
            var statusSelect = document.getElementById('status');
            if (newRemaining == 0 && discount > 0 && payment == 0) {
                statusSelect.value = 'waived';
            } else if (newRemaining == 0) {
                statusSelect.value = 'paid';
            } else if (newRemaining > 0 && (discount > 0 || payment > 0)) {
                statusSelect.value = 'partial';
            } else if (discount == 0 && payment == 0) {
                statusSelect.value = 'partial';
            }
        }

        function formatCurrency(value) {
            return 'Rp ' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        }

        function validateForm() {
            var discount = parseInt(document.getElementById('discount_amount').value) || 0;
            var payment = parseInt(document.getElementById('payment_amount').value) || 0;
            var originalRemaining = <?php echo $remaining; ?>;
            var total = discount + payment;
            
            if (total == 0) {
                alert('<?php echo __('Please enter discount amount or payment amount.'); ?>');
                return false;
            }
            
            if (total > originalRemaining) {
                alert('<?php echo __('Total discount + payment cannot exceed remaining balance.'); ?>');
                return false;
            }
            
            if (discount > 0 && document.getElementById('discount_reason').value.trim() == '') {
                alert('<?php echo __('Please enter reason for discount.'); ?>');
                document.getElementById('discount_reason').focus();
                return false;
            }
            
            var confirmMsg = '<?php echo __('Are you sure to process this payment?'); ?>\n\n';
            if (discount > 0) {
                confirmMsg += '<?php echo __('Discount'); ?>: ' + formatCurrency(discount) + '\n';
                confirmMsg += '<?php echo __('Discount Reason'); ?>: ' + document.getElementById('discount_reason').value + '\n';
            }
            if (payment > 0) {
                confirmMsg += '<?php echo __('Payment'); ?>: ' + formatCurrency(payment) + '\n';
            }
            confirmMsg += '\n<?php echo __('New Remaining Balance'); ?>: ' + document.getElementById('new_remaining').textContent;
            
            return confirm(confirmMsg);
        }

        // Update remaining on load
        document.addEventListener('DOMContentLoaded', function() {
            updateRemaining();
        });
    </script>

</body>
</html>