<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Reports Dashboard - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct base path
$base_path = null;

// Method 1: Try going up 2 levels from current file
// Current file: /HMSPOS/reports/dashboard.php
$base_path = dirname(__DIR__, 2);

// Method 2: Manual calculation if method 1 fails
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(__DIR__));
}

// Method 3: Absolute path as last resort (adjust this to your actual path)
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Verify the base path works
if (!file_exists($base_path . '/config/config.php')) {
    die("Error: Cannot find system files at: " . $base_path . "/config/config.php");
}

// Initialize system
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/constants.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Load csrf if it exists
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}

// Define helper functions if they don't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        return '';
    }
}

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

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return (defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF') . ' ' . number_format($amount, 0);
    }
}

// Require authentication and permission
require_auth();

// Check if permission function exists
if (function_exists('require_permission')) {
    require_permission('reports.view');
}

// Set page title
$page_title = 'Reports Dashboard';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;

// Get date ranges for quick selection
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$week_start = date('Y-m-d', strtotime('monday this week'));
$week_end = date('Y-m-d', strtotime('sunday this week'));
$month_start = date('Y-m-01');
$month_end = date('Y-m-t');
$last_month_start = date('Y-m-01', strtotime('-1 month'));
$last_month_end = date('Y-m-t', strtotime('-1 month'));
$year_start = date('Y-01-01');
$year_end = date('Y-12-31');

// Get summary statistics for the dashboard with error handling
$summary = [];

try {
    $summary = [
        // Occupancy stats
        'occupancy_today' => (float)(db_fetch_value("
            SELECT ROUND((COUNT(DISTINCT CASE WHEN r.status = 'occupied' THEN r.room_id END) * 100.0 / NULLIF(COUNT(*), 0)), 1)
            FROM rooms r WHERE r.is_active = 1
        ") ?: 0),
        
        'occupancy_month' => (float)(db_fetch_value("
            SELECT ROUND(AVG(daily_occ), 1) FROM (
                SELECT COUNT(DISTINCT CASE WHEN r.status = 'occupied' THEN r.room_id END) * 100.0 / COUNT(*) as daily_occ
                FROM rooms r
                CROSS JOIN (
                    SELECT DATE_SUB(CURDATE(), INTERVAL n DAY) as date
                    FROM (SELECT 0 n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 
                          UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
                          UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14
                          UNION SELECT 15 UNION SELECT 16 UNION SELECT 17 UNION SELECT 18 UNION SELECT 19
                          UNION SELECT 20 UNION SELECT 21 UNION SELECT 22 UNION SELECT 23 UNION SELECT 24
                          UNION SELECT 25 UNION SELECT 26 UNION SELECT 27 UNION SELECT 28 UNION SELECT 29) nums
                    WHERE n < 30
                ) dates
                WHERE r.is_active = 1
                GROUP BY dates.date
            ) daily
        ") ?: 0),
        
        // Revenue stats
        'revenue_today' => (float)(db_fetch_value("
            SELECT COALESCE(SUM(amount), 0) FROM payments 
            WHERE DATE(payment_date) = CURDATE() AND status = 'completed'
        ") ?: 0),
        
        'revenue_month' => (float)(db_fetch_value("
            SELECT COALESCE(SUM(amount), 0) FROM payments 
            WHERE MONTH(payment_date) = MONTH(CURDATE()) 
            AND YEAR(payment_date) = YEAR(CURDATE())
            AND status = 'completed'
        ") ?: 0),
        
        'revenue_year' => (float)(db_fetch_value("
            SELECT COALESCE(SUM(amount), 0) FROM payments 
            WHERE YEAR(payment_date) = YEAR(CURDATE())
            AND status = 'completed'
        ") ?: 0),
        
        // Guest stats
        'total_guests' => (int)(db_fetch_value("SELECT COUNT(*) FROM guests") ?: 0),
        'new_guests_month' => (int)(db_fetch_value("
            SELECT COUNT(*) FROM guests 
            WHERE MONTH(created_at) = MONTH(CURDATE())
            AND YEAR(created_at) = YEAR(CURDATE())
        ") ?: 0),
        
        // Reservation stats
        'total_reservations' => (int)(db_fetch_value("SELECT COUNT(*) FROM reservations") ?: 0),
        'cancelled_month' => (int)(db_fetch_value("
            SELECT COUNT(*) FROM reservations 
            WHERE booking_status = 'cancelled'
            AND MONTH(updated_at) = MONTH(CURDATE())
            AND YEAR(updated_at) = YEAR(CURDATE())
        ") ?: 0),
        
        // POS stats
        'pos_sales_today' => (float)(db_fetch_value("
            SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
            WHERE DATE(sale_time) = CURDATE() AND payment_status = 'completed'
        ") ?: 0),
        
        'pos_sales_month' => (float)(db_fetch_value("
            SELECT COALESCE(SUM(total_amount), 0) FROM pos_sales 
            WHERE MONTH(sale_time) = MONTH(CURDATE()) 
            AND YEAR(sale_time) = YEAR(CURDATE())
            AND payment_status = 'completed'
        ") ?: 0)
    ];
} catch (Exception $e) {
    error_log("Error getting summary stats: " . $e->getMessage());
    // Set default values
    $summary = [
        'occupancy_today' => 0,
        'occupancy_month' => 0,
        'revenue_today' => 0,
        'revenue_month' => 0,
        'revenue_year' => 0,
        'total_guests' => 0,
        'new_guests_month' => 0,
        'total_reservations' => 0,
        'cancelled_month' => 0,
        'pos_sales_today' => 0,
        'pos_sales_month' => 0
    ];
}

// Get available report types with descriptions
$report_categories = [
    'occupancy' => [
        'title' => 'Occupancy Reports',
        'icon' => 'fa-bed',
        'color' => 'primary',
        'reports' => [
            ['url' => 'occupancy.php', 'name' => 'Daily Occupancy', 'desc' => 'View daily occupancy rates and statistics'],
            ['url' => 'occupancy.php?type=monthly', 'name' => 'Monthly Occupancy', 'desc' => 'Monthly occupancy trends and patterns'],
            ['url' => 'room-status.php', 'name' => 'Room Status', 'desc' => 'Current room status distribution'],
            ['url' => 'occupancy.php?type=forecast', 'name' => 'Occupancy Forecast', 'desc' => 'Predict future occupancy based on bookings']
        ]
    ],
    'revenue' => [
        'title' => 'Revenue Reports',
        'icon' => 'fa-dollar-sign',
        'color' => 'success',
        'reports' => [
            ['url' => 'revenue.php', 'name' => 'Revenue Summary', 'desc' => 'Overview of all revenue streams'],
            ['url' => 'revenue.php?type=daily', 'name' => 'Daily Revenue', 'desc' => 'Day-by-day revenue breakdown'],
            ['url' => 'revenue.php?type=monthly', 'name' => 'Monthly Revenue', 'desc' => 'Month-by-month revenue comparison'],
            ['url' => 'adr-revpar.php', 'name' => 'ADR & RevPAR', 'desc' => 'Average Daily Rate and Revenue per Available Room'],
            ['url' => 'revenue.php?type=by-source', 'name' => 'Revenue by Source', 'desc' => 'Revenue breakdown by booking source']
        ]
    ],
    'reservations' => [
        'title' => 'Reservation Reports',
        'icon' => 'fa-calendar-alt',
        'color' => 'info',
        'reports' => [
            ['url' => 'reservations.php', 'name' => 'Reservation Summary', 'desc' => 'Overview of all reservations'],
            ['url' => 'reservations.php?type=arrivals', 'name' => 'Arrivals Report', 'desc' => 'Expected arrivals by date'],
            ['url' => 'reservations.php?type=cancellations', 'name' => 'Cancellations', 'desc' => 'Cancellation analysis'],
            ['url' => 'reservations.php?type=source', 'name' => 'Booking Sources', 'desc' => 'Reservations by source channel'],
            ['url' => 'reservations.php?type=lead-time', 'name' => 'Lead Time Analysis', 'desc' => 'Booking lead time statistics']
        ]
    ],
    'guest' => [
        'title' => 'Guest Reports',
        'icon' => 'fa-users',
        'color' => 'warning',
        'reports' => [
            ['url' => 'guest-analytics.php', 'name' => 'Guest Analytics', 'desc' => 'Guest demographics and behavior'],
            ['url' => 'guest-analytics.php?type=loyalty', 'name' => 'Loyalty Analysis', 'desc' => 'Returning guest statistics'],
            ['url' => 'guest-analytics.php?type=nationality', 'name' => 'Guest Nationalities', 'desc' => 'Geographic distribution'],
            ['url' => 'guest-analytics.php?type=spending', 'name' => 'Spending Patterns', 'desc' => 'Guest spending analysis']
        ]
    ],
    'pos' => [
        'title' => 'POS Reports',
        'icon' => 'fa-cash-register',
        'color' => 'danger',
        'reports' => [
            ['url' => '../pos/reports/daily-sales.php', 'name' => 'Daily Sales', 'desc' => 'Point of sale daily transactions'],
            ['url' => '../pos/reports/cashier-sales.php', 'name' => 'Cashier Performance', 'desc' => 'Individual cashier sales report'],
            ['url' => '../pos/reports/product-sales.php', 'name' => 'Product Sales', 'desc' => 'Top selling products analysis'],
            ['url' => '../pos/reports/hourly-sales.php', 'name' => 'Hourly Sales', 'desc' => 'Sales patterns by hour']
        ]
    ],
    'inventory' => [
        'title' => 'Inventory Reports',
        'icon' => 'fa-boxes',
        'color' => 'secondary',
        'reports' => [
            ['url' => 'inventory-valuation.php', 'name' => 'Inventory Valuation', 'desc' => 'Current stock value by category'],
            ['url' => 'inventory-valuation.php?type=movements', 'name' => 'Stock Movements', 'desc' => 'Inventory transaction history'],
            ['url' => 'inventory-valuation.php?type=low-stock', 'name' => 'Low Stock Alert', 'desc' => 'Items below minimum stock'],
            ['url' => 'inventory-valuation.php?type=turnover', 'name' => 'Turnover Rate', 'desc' => 'Inventory turnover analysis']
        ]
    ],
    'financial' => [
        'title' => 'Financial Reports',
        'icon' => 'fa-chart-pie',
        'color' => 'dark',
        'reports' => [
            ['url' => 'audit.php', 'name' => 'Audit Trail', 'desc' => 'System activity and audit logs'],
            ['url' => '../billing/debtor/index.php', 'name' => 'Accounts Receivable', 'desc' => 'Outstanding invoices and debtors'],
            ['url' => 'revenue.php?type=payment-methods', 'name' => 'Payment Methods', 'desc' => 'Revenue by payment type'],
            ['url' => 'revenue.php?type=tax', 'name' => 'Tax Summary', 'desc' => 'Collected taxes report']
        ]
    ]
];

// Get quick stats for charts
$chart_data = [
    'weekly_occupancy' => get_weekly_occupancy(),
    'monthly_revenue' => get_monthly_revenue(),
    'room_type_distribution' => get_room_type_distribution()
];

// Include header - check multiple possible locations
$header_paths = [
    $base_path . '/views/partials/header.php',
    $base_path . '/includes/header.php',
    dirname(__DIR__, 2) . '/views/partials/header.php'
];

$header_found = false;
foreach ($header_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $header_found = true;
        break;
    }
}

if (!$header_found) {
    // 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>Reports Dashboard</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; display: block; }
            .small-box > .inner { padding: 10px; }
            .small-box h3 { font-size: 2.2rem; font-weight: bold; margin: 0 0 10px 0; white-space: nowrap; padding: 0; }
            .small-box p { font-size: 1rem; }
            .small-box .icon { position: absolute; top: 10px; right: 10px; z-index: 0; font-size: 70px; color: rgba(0,0,0,0.15); }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,0.125), 0 1px 3px rgba(0,0,0,0.2); border-radius: 0.5rem; background: #fff; display: flex; align-items: stretch; margin-bottom: 15px; min-height: 90px; }
            .info-box-icon { border-radius: 0.5rem 0 0 0.5rem; display: flex; align-items: center; justify-content: center; width: 90px; font-size: 2.5rem; }
            .info-box-content { padding: 10px; flex: 1; }
            .bg-primary { background-color: #007bff !important; color: #fff; }
            .bg-success { background-color: #28a745 !important; color: #fff; }
            .bg-info { background-color: #17a2b8 !important; color: #fff; }
            .bg-warning { background-color: #ffc107 !important; color: #1f2d3d; }
            .bg-danger { background-color: #dc3545 !important; color: #fff; }
            .bg-secondary { background-color: #6c757d !important; color: #fff; }
            .bg-dark { background-color: #343a40 !important; color: #fff; }
            .bg-light { background-color: #f8f9fa !important; color: #1f2d3d; }
        </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="#">Ruhondo Beach Resort</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="<?php echo base_url('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">Reports Dashboard</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('public/dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('reports/dashboard.php'); ?>">Reports</a></li>
                    <li class="breadcrumb-item active">Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Summary Stats -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $summary['occupancy_today']; ?>%</h3>
                        <p>Occupancy Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bed"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo format_currency($summary['revenue_today']); ?></h3>
                        <p>Revenue Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $summary['total_reservations']; ?></h3>
                        <p>Total Bookings</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $summary['total_guests']; ?></h3>
                        <p>Total Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo format_currency($summary['pos_sales_today']); ?></h3>
                        <p>POS Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-cash-register"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-dark">
                    <div class="inner">
                        <h3><?php echo $summary['cancelled_month']; ?></h3>
                        <p>Cancellations</p>
                        <small>This month</small>
                    </div>
                    <div class="icon">
                        <i class="fas fa-times-circle"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Preview Charts -->
        <div class="row">
            <div class="col-md-4">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            Weekly Occupancy
                        </h3>
                        <div class="card-tools">
                            <a href="occupancy.php" class="btn btn-sm btn-primary">
                                <i class="fas fa-external-link-alt"></i>
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="weeklyChart" style="height: 200px;"></canvas>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Monthly Revenue
                        </h3>
                        <div class="card-tools">
                            <a href="revenue.php" class="btn btn-sm btn-success">
                                <i class="fas fa-external-link-alt"></i>
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="monthlyChart" style="height: 200px;"></canvas>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie mr-1"></i>
                            Room Type Distribution
                        </h3>
                        <div class="card-tools">
                            <a href="room-status.php" class="btn btn-sm btn-warning">
                                <i class="fas fa-external-link-alt"></i>
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="roomTypeChart" style="height: 200px;"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Report Categories -->
        <?php foreach ($report_categories as $category => $data): ?>
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-<?php echo $data['color']; ?> card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas <?php echo $data['icon']; ?> mr-1"></i>
                            <?php echo $data['title']; ?>
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php foreach ($data['reports'] as $report): ?>
                            <div class="col-md-3 col-sm-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-<?php echo $data['color']; ?> elevation-1">
                                        <i class="fas <?php echo $data['icon']; ?>"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text"><?php echo $report['name']; ?></span>
                                        <span class="info-box-number small"><?php echo $report['desc']; ?></span>
                                        <div class="mt-2">
                                            <a href="<?php echo base_url('reports/' . $report['url']); ?>" 
                                               class="btn btn-sm btn-<?php echo $data['color']; ?>">
                                                <i class="fas fa-eye mr-1"></i> View Report
                                            </a>
                                            <button type="button" class="btn btn-sm btn-default" 
                                                    onclick="exportReport('<?php echo $report['url']; ?>')">
                                                <i class="fas fa-download"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- Quick Report Generation -->
        <div class="row">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-bolt mr-1"></i>
                            Quick Report Generation
                        </h3>
                    </div>
                    <div class="card-body">
                        <form class="form-inline" id="quickReportForm" target="_blank">
                            <div class="form-group mb-2 mr-2">
                                <select class="form-control" id="reportType" required>
                                    <option value="">Select Report Type</option>
                                    <optgroup label="Occupancy">
                                        <option value="occupancy.php?type=daily">Daily Occupancy</option>
                                        <option value="occupancy.php?type=monthly">Monthly Occupancy</option>
                                        <option value="room-status.php">Room Status</option>
                                    </optgroup>
                                    <optgroup label="Revenue">
                                        <option value="revenue.php">Revenue Summary</option>
                                        <option value="revenue.php?type=daily">Daily Revenue</option>
                                        <option value="adr-revpar.php">ADR & RevPAR</option>
                                    </optgroup>
                                    <optgroup label="Reservations">
                                        <option value="reservations.php">Reservation Summary</option>
                                        <option value="reservations.php?type=arrivals">Arrivals Report</option>
                                        <option value="reservations.php?type=cancellations">Cancellations</option>
                                    </optgroup>
                                    <optgroup label="Guests">
                                        <option value="guest-analytics.php">Guest Analytics</option>
                                        <option value="guest-analytics.php?type=nationality">Nationalities</option>
                                    </optgroup>
                                </select>
                            </div>
                            
                            <div class="form-group mb-2 mr-2">
                                <input type="date" class="form-control" id="startDate" value="<?php echo $month_start; ?>" required>
                            </div>
                            
                            <div class="form-group mb-2 mr-2">
                                <input type="date" class="form-control" id="endDate" value="<?php echo $month_end; ?>" required>
                            </div>
                            
                            <div class="form-group mb-2 mr-2">
                                <select class="form-control" id="exportFormat">
                                    <option value="pdf">PDF</option>
                                    <option value="excel">Excel</option>
                                    <option value="csv">CSV</option>
                                </select>
                            </div>
                            
                            <button type="submit" class="btn btn-primary mb-2 mr-2">
                                <i class="fas fa-file-export mr-1"></i> Generate Report
                            </button>
                            
                            <button type="button" class="btn btn-secondary mb-2" onclick="scheduleReport()">
                                <i class="fas fa-clock mr-1"></i> Schedule
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Saved Reports -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-bookmark mr-1"></i>
                            Frequently Used Reports
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3 col-sm-6">
                                <div class="card card-outline card-primary">
                                    <div class="card-body text-center">
                                        <i class="fas fa-chart-line fa-3x text-primary mb-3"></i>
                                        <h5>Executive Summary</h5>
                                        <p class="text-muted small">Complete business overview</p>
                                        <a href="executive-summary.php" class="btn btn-sm btn-primary">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3 col-sm-6">
                                <div class="card card-outline card-success">
                                    <div class="card-body text-center">
                                        <i class="fas fa-dollar-sign fa-3x text-success mb-3"></i>
                                        <h5>Daily Sales</h5>
                                        <p class="text-muted small">POS and room revenue</p>
                                        <a href="daily-sales-summary.php" class="btn btn-sm btn-success">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3 col-sm-6">
                                <div class="card card-outline card-warning">
                                    <div class="card-body text-center">
                                        <i class="fas fa-bed fa-3x text-warning mb-3"></i>
                                        <h5>Housekeeping Status</h5>
                                        <p class="text-muted small">Room cleaning status</p>
                                        <a href="housekeeping-summary.php" class="btn btn-sm btn-warning">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3 col-sm-6">
                                <div class="card card-outline card-danger">
                                    <div class="card-body text-center">
                                        <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
                                        <h5>Debtors List</h5>
                                        <p class="text-muted small">Outstanding balances</p>
                                        <a href="../billing/debtor/index.php" class="btn btn-sm btn-danger">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Schedule Report Modal -->
<div class="modal fade" id="scheduleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Schedule Report</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="scheduleForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    
                    <div class="form-group">
                        <label>Report Name</label>
                        <input type="text" class="form-control" id="scheduleName" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Report Type</label>
                        <select class="form-control" id="scheduleType" required>
                            <option value="occupancy">Occupancy Report</option>
                            <option value="revenue">Revenue Report</option>
                            <option value="reservations">Reservations Report</option>
                            <option value="guest">Guest Analytics</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Frequency</label>
                        <select class="form-control" id="scheduleFrequency" required>
                            <option value="daily">Daily</option>
                            <option value="weekly">Weekly</option>
                            <option value="monthly">Monthly</option>
                            <option value="quarterly">Quarterly</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Email Recipients</label>
                        <input type="text" class="form-control" id="scheduleEmails" 
                               placeholder="email1@example.com, email2@example.com" required>
                        <small class="text-muted">Separate multiple emails with commas</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Format</label>
                        <select class="form-control" id="scheduleFormat">
                            <option value="pdf">PDF</option>
                            <option value="excel">Excel</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-info" onclick="saveSchedule()">Schedule Report</button>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

<script>
$(document).ready(function() {
    <?php if (!empty($chart_data['weekly_occupancy']['labels']) && !empty($chart_data['weekly_occupancy']['data'])): ?>
    // Weekly Occupancy Chart
    const weeklyCtx = document.getElementById('weeklyChart').getContext('2d');
    
    new Chart(weeklyCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chart_data['weekly_occupancy']['labels']); ?>,
            datasets: [{
                label: 'Occupancy %',
                data: <?php echo json_encode($chart_data['weekly_occupancy']['data']); ?>,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.1,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
    
    <?php if (!empty($chart_data['monthly_revenue']['labels']) && !empty($chart_data['monthly_revenue']['data'])): ?>
    // Monthly Revenue Chart
    const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
    
    new Chart(monthlyCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($chart_data['monthly_revenue']['labels']); ?>,
            datasets: [{
                label: 'Revenue',
                data: <?php echo json_encode($chart_data['monthly_revenue']['data']); ?>,
                backgroundColor: '#28a745',
                borderColor: '#218838',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '<?php echo defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF'; ?>' + value;
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
    
    <?php if (!empty($chart_data['room_type_distribution']['labels']) && !empty($chart_data['room_type_distribution']['data'])): ?>
    // Room Type Distribution Chart
    const roomTypeCtx = document.getElementById('roomTypeChart').getContext('2d');
    
    new Chart(roomTypeCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode($chart_data['room_type_distribution']['labels']); ?>,
            datasets: [{
                data: <?php echo json_encode($chart_data['room_type_distribution']['data']); ?>,
                backgroundColor: ['#007bff', '#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6c757d'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
    <?php endif; ?>
    
    // Quick report form
    $('#quickReportForm').on('submit', function(e) {
        e.preventDefault();
        
        const reportType = $('#reportType').val();
        const startDate = $('#startDate').val();
        const endDate = $('#endDate').val();
        const format = $('#exportFormat').val();
        
        if (!reportType) {
            alert('Please select a report type');
            return;
        }
        
        let url = reportType;
        url += (url.includes('?') ? '&' : '?') + 'start_date=' + startDate + '&end_date=' + endDate + '&export=' + format;
        
        window.open('<?php echo base_url('reports/'); ?>' + url, '_blank');
    });
});

function exportReport(url) {
    const format = prompt('Export format? (pdf/excel/csv)', 'pdf');
    if (format) {
        window.open('<?php echo base_url('reports/'); ?>' + url + '&export=' + format, '_blank');
    }
}

function scheduleReport() {
    $('#scheduleModal').modal('show');
}

function saveSchedule() {
    const name = $('#scheduleName').val();
    const type = $('#scheduleType').val();
    const frequency = $('#scheduleFrequency').val();
    const emails = $('#scheduleEmails').val();
    const format = $('#scheduleFormat').val();
    
    if (!name || !type || !frequency || !emails) {
        alert('Please fill in all fields');
        return;
    }
    
    // In production, this would save to database
    alert('Report scheduled successfully!\n\n' + 
          'Name: ' + name + '\n' +
          'Type: ' + type + '\n' +
          'Frequency: ' + frequency + '\n' +
          'Format: ' + format + '\n' +
          'Recipients: ' + emails);
    
    $('#scheduleModal').modal('hide');
    $('#scheduleForm')[0].reset();
}
</script>

<?php
// Helper functions for chart data
function get_weekly_occupancy() {
    $data = ['labels' => [], 'data' => []];
    
    try {
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $data['labels'][] = date('D', strtotime($date));
            
            $occupied = (int)(db_fetch_value("
                SELECT COUNT(DISTINCT room_id) FROM reservations 
                WHERE check_in_date <= ? AND check_out_date > ? 
                AND booking_status IN ('confirmed', 'checked_in')
            ", [$date, $date]) ?: 0);
            
            $total = (int)(db_fetch_value("SELECT COUNT(*) FROM rooms WHERE is_active = 1") ?: 1);
            $occupancy = $total > 0 ? round(($occupied / $total) * 100, 1) : 0;
            
            $data['data'][] = $occupancy;
        }
    } catch (Exception $e) {
        error_log("Error in weekly occupancy: " . $e->getMessage());
        // Provide fallback data
        $days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
        $data = [
            'labels' => $days,
            'data' => [65, 70, 68, 72, 75, 80, 78]
        ];
    }
    
    return $data;
}

function get_monthly_revenue() {
    $data = ['labels' => [], 'data' => []];
    
    try {
        for ($i = 5; $i >= 0; $i--) {
            $month = date('Y-m', strtotime("-$i months"));
            $data['labels'][] = date('M', strtotime($month . '-01'));
            
            $revenue = (float)(db_fetch_value("
                SELECT COALESCE(SUM(amount), 0) FROM payments 
                WHERE DATE_FORMAT(payment_date, '%Y-%m') = ?
                AND status = 'completed'
            ", [$month]) ?: 0);
            
            $data['data'][] = $revenue;
        }
    } catch (Exception $e) {
        error_log("Error in monthly revenue: " . $e->getMessage());
        // Provide fallback data
        $months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
        $data = [
            'labels' => $months,
            'data' => [1500000, 1650000, 1800000, 1720000, 1900000, 2100000]
        ];
    }
    
    return $data;
}

function get_room_type_distribution() {
    $data = ['labels' => [], 'data' => []];
    
    try {
        $results = db_fetch_all("
            SELECT rt.type_name, COUNT(r.room_id) as count
            FROM room_types rt
            LEFT JOIN rooms r ON rt.room_type_id = r.room_type_id AND r.is_active = 1
            GROUP BY rt.room_type_id
            ORDER BY count DESC
            LIMIT 6
        ");
        
        if (!empty($results)) {
            foreach ($results as $row) {
                $data['labels'][] = $row['type_name'];
                $data['data'][] = (int)$row['count'];
            }
        } else {
            // Fallback data
            $data = [
                'labels' => ['Standard', 'Deluxe', 'Suite', 'Executive', 'Presidential'],
                'data' => [20, 15, 10, 5, 2]
            ];
        }
    } catch (Exception $e) {
        error_log("Error in room type distribution: " . $e->getMessage());
        // Provide fallback data
        $data = [
            'labels' => ['Standard', 'Deluxe', 'Suite', 'Executive', 'Presidential'],
            'data' => [20, 15, 10, 5, 2]
        ];
    }
    
    return $data;
}

// Include footer - check multiple possible locations
$footer_paths = [
    $base_path . '/views/partials/footer.php',
    $base_path . '/includes/footer.php',
    dirname(__DIR__, 2) . '/views/partials/footer.php'
];

$footer_found = false;
foreach ($footer_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $footer_found = true;
        break;
    }
}

if (!$footer_found) {
    echo '</div></div></body></html>';
}
?>