<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Debtors Management - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/billing/debtors/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/billing/debtors/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define display_flash_messages function if it doesn't exist
if (!function_exists('display_flash_messages')) {
    function display_flash_messages() {
        if (isset($_SESSION['flash_messages']) && is_array($_SESSION['flash_messages'])) {
            foreach ($_SESSION['flash_messages'] as $msg) {
                $type = $msg['type'] ?? 'info';
                $message = $msg['message'] ?? '';
                echo "<div class='alert alert-{$type} alert-dismissible fade show'>";
                echo escape_html($message);
                echo "<button type='button' class='btn-close' data-bs-dismiss='alert'></button>";
                echo "</div>";
            }
            unset($_SESSION['flash_messages']);
        }
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define constants if not defined
if (!defined('ITEMS_PER_PAGE')) {
    define('ITEMS_PER_PAGE', 25);
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('billing.debtors.view');
}

// Set page title
$page_title = 'Debtors Management';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status = isset($_GET['status']) ? $_GET['status'] : 'all';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'balance';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE : 25;

// Build where clause for debtor query
$where = "i.status IN ('sent', 'partial', 'overdue') AND i.balance > 0";
$params = [];

if (!empty($search)) {
    $where .= " AND (g.first_name LIKE ? OR g.last_name LIKE ? OR g.email LIKE ? OR i.invoice_number LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term]);
}

if ($status === 'overdue') {
    $where .= " AND i.status = 'overdue'";
} elseif ($status === 'partial') {
    $where .= " AND i.status = 'partial'";
} elseif ($status === 'sent') {
    $where .= " AND i.status = 'sent'";
}

// Get debtors list with summary
$debtors = [];
$total = 0;

if (function_exists('db_fetch_value') && function_exists('db_fetch_all')) {
    try {
        // Get total count (unique guests)
        $count_sql = "
            SELECT COUNT(DISTINCT g.guest_id)
            FROM guests g
            JOIN invoices i ON g.guest_id = i.guest_id
            WHERE $where
        ";
        $total = db_fetch_value($count_sql, $params) ?: 0;

        // Get paginated data
        $offset = ($page - 1) * $per_page;
        
        $sql = "
            SELECT 
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                COUNT(DISTINCT i.invoice_id) as invoice_count,
                COALESCE(SUM(i.balance), 0) as total_balance,
                MAX(i.due_date) as oldest_invoice,
                MIN(i.due_date) as newest_invoice,
                COALESCE(SUM(CASE WHEN i.status = 'overdue' THEN i.balance ELSE 0 END), 0) as overdue_amount,
                COUNT(CASE WHEN i.status = 'overdue' THEN 1 END) as overdue_count
            FROM guests g
            JOIN invoices i ON g.guest_id = i.guest_id
            WHERE $where
            GROUP BY g.guest_id
            HAVING total_balance > 0
            ORDER BY 
                CASE WHEN '$sort' = 'balance' THEN total_balance END $order,
                CASE WHEN '$sort' = 'name' THEN g.first_name END $order,
                CASE WHEN '$sort' = 'invoices' THEN invoice_count END $order
            LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
        
        $debtors = db_fetch_all($sql, $params) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching debtors: " . $e->getMessage());
    }
}

// Calculate pagination
$total_pages = $per_page > 0 ? ceil($total / $per_page) : 0;

// Get summary statistics
$stats = [
    'total_debtors' => $total,
    'total_outstanding' => 0,
    'overdue_amount' => 0,
    'overdue_count' => 0,
    'avg_debt' => 0
];

if (function_exists('db_fetch_value')) {
    try {
        $stats['total_outstanding'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE status IN ('sent', 'partial', 'overdue')") ?: 0;
        $stats['overdue_amount'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE status = 'overdue'") ?: 0;
        $stats['overdue_count'] = db_fetch_value("SELECT COUNT(*) FROM invoices WHERE status = 'overdue'") ?: 0;
        $stats['avg_debt'] = db_fetch_value("SELECT COALESCE(AVG(balance), 0) FROM invoices WHERE status IN ('sent', 'partial', 'overdue')") ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching stats: " . $e->getMessage());
    }
}

// Get aging summary
$aging = [
    'current' => 0,
    '1_30' => 0,
    '31_60' => 0,
    '61_90' => 0,
    '90_plus' => 0
];

if (function_exists('db_fetch_value')) {
    try {
        $aging['current'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE DATEDIFF(CURDATE(), due_date) <= 0 AND status IN ('sent', 'partial')") ?: 0;
        $aging['1_30'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE DATEDIFF(CURDATE(), due_date) BETWEEN 1 AND 30 AND status = 'overdue'") ?: 0;
        $aging['31_60'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE DATEDIFF(CURDATE(), due_date) BETWEEN 31 AND 60 AND status = 'overdue'") ?: 0;
        $aging['61_90'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE DATEDIFF(CURDATE(), due_date) BETWEEN 61 AND 90 AND status = 'overdue'") ?: 0;
        $aging['90_plus'] = db_fetch_value("SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE DATEDIFF(CURDATE(), due_date) > 90 AND status = 'overdue'") ?: 0;
    } catch (Exception $e) {
        error_log("Error fetching aging: " . $e->getMessage());
    }
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Debtors Management</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); border-radius: 0.25rem; background: #fff; display: flex; margin-bottom: 20px; min-height: 80px; }
            .info-box-content { padding: 10px; flex: 1; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
            .bg-secondary { background-color: #6c757d !important; }
            .bg-light { background-color: #f8f9fa !important; }
            .text-orange { color: #fd7e14; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mt-2 { margin-top: 0.5rem; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Debtors Management</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Debtors Management</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/billing/dashboard.php">Billing</a></li>
                    <li class="breadcrumb-item active">Debtors</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php display_flash_messages(); ?>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total_debtors']; ?></h3>
                        <p>Total Debtors</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_outstanding']); ?></h3>
                        <p>Total Outstanding</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['overdue_amount']); ?></h3>
                        <p>Overdue Amount</p>
                        <small><?php echo $stats['overdue_count']; ?> invoices</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['avg_debt']); ?></h3>
                        <p>Average Debt</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Aging Summary -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clock me-1"></i>
                            Aging Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-2 col-6">
                                <div class="info-box bg-light">
                                    <div class="info-box-content text-center">
                                        <span class="info-box-text">Current</span>
                                        <span class="info-box-number"><?php echo format_currency($aging['current']); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 col-6">
                                <div class="info-box bg-light">
                                    <div class="info-box-content text-center">
                                        <span class="info-box-text">1-30 Days</span>
                                        <span class="info-box-number text-warning"><?php echo format_currency($aging['1_30']); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 col-6">
                                <div class="info-box bg-light">
                                    <div class="info-box-content text-center">
                                        <span class="info-box-text">31-60 Days</span>
                                        <span class="info-box-number text-orange"><?php echo format_currency($aging['31_60']); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 col-6">
                                <div class="info-box bg-light">
                                    <div class="info-box-content text-center">
                                        <span class="info-box-text">61-90 Days</span>
                                        <span class="info-box-number text-danger"><?php echo format_currency($aging['61_90']); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 col-6">
                                <div class="info-box bg-light">
                                    <div class="info-box-content text-center">
                                        <span class="info-box-text">90+ Days</span>
                                        <span class="info-box-number text-danger"><?php echo format_currency($aging['90_plus']); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 col-6">
                                <div class="info-box bg-light">
                                    <div class="info-box-content text-center">
                                        <span class="info-box-text">Total</span>
                                        <span class="info-box-number"><?php echo format_currency($stats['total_outstanding']); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <input type="text" class="form-control" name="search" placeholder="Search guest or invoice..." 
                               value="<?php echo escape_html($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="all" <?php echo $status == 'all' ? 'selected' : ''; ?>>All Debtors</option>
                            <option value="sent" <?php echo $status == 'sent' ? 'selected' : ''; ?>>Sent (Not Due)</option>
                            <option value="partial" <?php echo $status == 'partial' ? 'selected' : ''; ?>>Partial Payment</option>
                            <option value="overdue" <?php echo $status == 'overdue' ? 'selected' : ''; ?>>Overdue</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="sort">
                            <option value="balance" <?php echo $sort == 'balance' ? 'selected' : ''; ?>>Sort by Balance</option>
                            <option value="name" <?php echo $sort == 'name' ? 'selected' : ''; ?>>Sort by Name</option>
                            <option value="invoices" <?php echo $sort == 'invoices' ? 'selected' : ''; ?>>Sort by Invoice Count</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="order">
                            <option value="DESC" <?php echo $order == 'DESC' ? 'selected' : ''; ?>>Descending</option>
                            <option value="ASC" <?php echo $order == 'ASC' ? 'selected' : ''; ?>>Ascending</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search me-1"></i> Apply
                        </button>
                    </div>
                    
                    <div class="col-md-2">
                        <a href="?" class="btn btn-secondary w-100">
                            <i class="fas fa-times me-1"></i> Clear
                        </a>
                    </div>
                    
                    <div class="col-md-2 ms-auto">
                        <button type="button" class="btn btn-info w-100" onclick="exportDebtors()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Debtors Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-list me-1"></i>
                    Debtors List (<?php echo $total; ?> total)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($debtors)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-check-circle fa-4x mb-3 text-success"></i>
                        <h5>No debtors found</h5>
                        <p>All invoices are paid in full</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Guest</th>
                                    <th>Contact</th>
                                    <th class="text-center">Invoices</th>
                                    <th class="text-end">Total Balance</th>
                                    <th class="text-end">Overdue Amount</th>
                                    <th class="text-center">Overdue Invoices</th>
                                    <th>Oldest Invoice</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($debtors as $debtor): ?>
                                <tr>
                                    <td>
                                        <a href="/HMSPOS/guests/view.php?id=<?php echo $debtor['guest_id'] ?? 0; ?>">
                                            <strong><?php echo escape_html(($debtor['first_name'] ?? '') . ' ' . ($debtor['last_name'] ?? '')); ?></strong>
                                        </a>
                                    </td>
                                    <td>
                                        <?php if (!empty($debtor['email'])): ?>
                                            <i class="fas fa-envelope text-muted"></i> <?php echo escape_html($debtor['email']); ?><br>
                                        <?php endif; ?>
                                        <?php if (!empty($debtor['phone'])): ?>
                                            <i class="fas fa-phone text-muted"></i> <?php echo escape_html($debtor['phone']); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $debtor['invoice_count'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-end">
                                        <strong class="text-danger"><?php echo format_currency($debtor['total_balance'] ?? 0); ?></strong>
                                    </td>
                                    <td class="text-end">
                                        <?php if (!empty($debtor['overdue_amount']) && $debtor['overdue_amount'] > 0): ?>
                                            <span class="text-danger"><?php echo format_currency($debtor['overdue_amount']); ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if (!empty($debtor['overdue_count']) && $debtor['overdue_count'] > 0): ?>
                                            <span class="badge bg-danger"><?php echo $debtor['overdue_count']; ?></span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">0</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        if (!empty($debtor['oldest_invoice'])) {
                                            $oldest = new DateTime($debtor['oldest_invoice']);
                                            $today = new DateTime();
                                            $days = $today->diff($oldest)->days;
                                            echo date('M d, Y', strtotime($debtor['oldest_invoice']));
                                            echo "<br><small class='text-muted'>$days days</small>";
                                        } else {
                                            echo '-';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="statement.php?guest_id=<?php echo $debtor['guest_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View Statement">
                                                <i class="fas fa-file-invoice"></i>
                                            </a>
                                            
                                            <a href="../payments/add.php?guest_id=<?php echo $debtor['guest_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-success" title="Record Payment">
                                                <i class="fas fa-dollar-sign"></i>
                                            </a>
                                            
                                            <button type="button" class="btn btn-sm btn-warning" 
                                                    onclick="sendReminder(<?php echo $debtor['guest_id'] ?? 0; ?>)"
                                                    title="Send Reminder">
                                                <i class="fas fa-envelope"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer clearfix">
                <div class="row">
                    <div class="col-sm-5">
                        <span class="text-muted">
                            Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $per_page, $total); ?> of <?php echo $total; ?> debtors
                        </span>
                    </div>
                    <div class="col-sm-7">
                        <ul class="pagination pagination-sm m-0 float-end">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Send Reminder Modal -->
<div class="modal fade" id="reminderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Send Payment Reminder</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="send-reminder.php" method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                <?php endif; ?>
                <input type="hidden" name="guest_id" id="reminder_guest_id">
                
                <div class="modal-body">
                    <p>Send payment reminder to guest?</p>
                    
                    <div class="form-group mb-3">
                        <label for="reminder_message">Additional Message</label>
                        <textarea class="form-control" id="reminder_message" name="message" rows="3"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Send Reminder</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function sendReminder(guestId) {
    $('#reminder_guest_id').val(guestId);
    
    // Initialize Bootstrap 5 modal
    const reminderModal = new bootstrap.Modal(document.getElementById('reminderModal'));
    reminderModal.show();
}

function exportDebtors() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.location.href = 'export.php?' + params.toString();
}
</script>

<style>
.text-orange {
    color: #fd7e14;
}
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>