<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Rates Management Dashboard - FIXED VERSION
 * 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
// Current file: /HMSPOS/rooms/rates/index.php
// Need to go up to: /HMSPOS/
$base_path = null;

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

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

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

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// 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 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 format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

// 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');
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('rates.view');
// }

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

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

// Initialize stats with default values
$stats = [
    'total_rate_plans' => 0,
    'active_seasons' => 0,
    'price_rules' => 0,
    'room_types_with_rates' => 0
];

// Get statistics with error handling
try {
    $stats['total_rate_plans'] = (int)db_fetch_value("SELECT COUNT(*) FROM rate_plans WHERE is_active = 1") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching rate plans count: " . $e->getMessage());
}

try {
    $stats['active_seasons'] = (int)db_fetch_value("SELECT COUNT(*) FROM seasons WHERE is_active = 1 AND end_date >= CURDATE()") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching seasons count: " . $e->getMessage());
}

try {
    $stats['price_rules'] = (int)db_fetch_value("SELECT COUNT(*) FROM price_rules WHERE is_active = 1") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching price rules count: " . $e->getMessage());
}

try {
    $stats['room_types_with_rates'] = (int)db_fetch_value("SELECT COUNT(DISTINCT room_type_id) FROM rate_plans") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching room types with rates: " . $e->getMessage());
}

// Get recent rate plans
$recent_plans = [];
try {
    $recent_plans = db_fetch_all("
        SELECT rp.*, rt.type_name, s.season_name
        FROM rate_plans rp
        JOIN room_types rt ON rp.room_type_id = rt.room_type_id
        LEFT JOIN seasons s ON rp.season_id = s.season_id
        ORDER BY rp.created_at DESC
        LIMIT 10
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching recent plans: " . $e->getMessage());
}

// Get active seasons
$active_seasons = [];
try {
    $active_seasons = db_fetch_all("
        SELECT * FROM seasons 
        WHERE is_active = 1 
        AND end_date >= CURDATE()
        ORDER BY start_date
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching active seasons: " . $e->getMessage());
}

// Get current rates by room type
$current_rates = [];
try {
    $current_rates = db_fetch_all("
        SELECT 
            rt.room_type_id,
            rt.type_name,
            rt.type_code,
            rt.base_price,
            MIN(rp.base_rate) as min_rate,
            MAX(rp.base_rate) as max_rate,
            COUNT(rp.rate_plan_id) as plan_count
        FROM room_types rt
        LEFT JOIN rate_plans rp ON rt.room_type_id = rp.room_type_id AND rp.is_active = 1
        WHERE rt.is_active = 1
        GROUP BY rt.room_type_id
        ORDER BY rt.type_name
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching current rates: " . $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>Rates 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; }
            .small-box-footer { display: block; padding: 10px; text-align: center; background: rgba(0,0,0,0.1); color: #fff; text-decoration: none; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-success { background-color: #28a745 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
        </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="#">Rates 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">Rates 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/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item active">Rates</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Stats 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_rate_plans']; ?></h3>
                        <p>Active Rate Plans</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tags"></i>
                    </div>
                    <a href="rate-plans.php" class="small-box-footer">
                        Manage Rates <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['active_seasons']; ?></h3>
                        <p>Active Seasons</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-alt"></i>
                    </div>
                    <a href="seasons.php" class="small-box-footer">
                        Manage Seasons <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['price_rules']; ?></h3>
                        <p>Price Rules</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-cogs"></i>
                    </div>
                    <a href="price-rules.php" class="small-box-footer">
                        Manage Rules <i class="fas fa-arrow-circle-right"></i>
                    </a>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['room_types_with_rates']; ?></h3>
                        <p>Room Types with Rates</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bed"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="rate-plans.php?action=create" class="btn btn-primary me-2 mb-2">
                            <i class="fas fa-plus-circle me-1"></i> New Rate Plan
                        </a>
                        <a href="seasons.php?action=create" class="btn btn-success me-2 mb-2">
                            <i class="fas fa-plus-circle me-1"></i> New Season
                        </a>
                        <a href="price-rules.php?action=create" class="btn btn-warning me-2 mb-2">
                            <i class="fas fa-plus-circle me-1"></i> New Price Rule
                        </a>
                        <a href="../availability/calendar.php" class="btn btn-info me-2 mb-2">
                            <i class="fas fa-calendar-alt me-1"></i> View Calendar
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Current Rates by Room Type -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar me-1"></i>
                            Current Rates by Room Type
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Room Type</th>
                                        <th class="text-end">Base Price</th>
                                        <th class="text-end">Rate Range</th>
                                        <th class="text-center">Plans</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($current_rates)): ?>
                                        <tr>
                                            <td colspan="5" class="text-center text-muted py-3">
                                                No room types found
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($current_rates as $rate): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape_html($rate['type_name'] ?? ''); ?></strong>
                                                <br>
                                                <small><?php echo escape_html($rate['type_code'] ?? ''); ?></small>
                                            </td>
                                            <td class="text-end">
                                                <span class="text-muted"><?php echo format_currency($rate['base_price'] ?? 0); ?></span>
                                            </td>
                                            <td class="text-end">
                                                <?php if (!empty($rate['min_rate'])): ?>
                                                    <?php echo format_currency($rate['min_rate']); ?> - <?php echo format_currency($rate['max_rate']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">No rate plans</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge bg-info"><?php echo $rate['plan_count'] ?? 0; ?></span>
                                            </td>
                                            <td>
                                                <a href="rate-plans.php?room_type_id=<?php echo $rate['room_type_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-primary">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Active Seasons -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calendar-alt me-1"></i>
                            Active Seasons
                        </h3>
                        <div class="card-tools">
                            <a href="seasons.php" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($active_seasons)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar fa-3x mb-3"></i>
                                <p>No active seasons</p>
                                <a href="seasons.php?action=create" class="btn btn-sm btn-success">
                                    Create Season
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Season</th>
                                            <th>Period</th>
                                            <th class="text-end">Multiplier</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($active_seasons as $season): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape_html($season['season_name'] ?? ''); ?></strong>
                                            </td>
                                            <td>
                                                <?php echo format_date($season['start_date'] ?? ''); ?> - <?php echo format_date($season['end_date'] ?? ''); ?>
                                                <?php 
                                                if (!empty($season['end_date'])) {
                                                    $days_left = (strtotime($season['end_date']) - time()) / 86400;
                                                    if ($days_left <= 7):
                                                    ?>
                                                        <br>
                                                        <small class="text-danger"><?php echo round($days_left); ?> days left</small>
                                                    <?php 
                                                    endif;
                                                }
                                                ?>
                                            </td>
                                            <td class="text-end">
                                                <span class="badge bg-info"><?php echo $season['multiplier'] ?? 1; ?>x</span>
                                            </td>
                                            <td>
                                                <span class="badge bg-success">Active</span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Recent Rate Plans -->
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history me-1"></i>
                            Recent Rate Plans
                        </h3>
                        <div class="card-tools">
                            <a href="rate-plans.php" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_plans)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-tags fa-3x mb-3"></i>
                                <p>No rate plans created yet</p>
                                <a href="rate-plans.php?action=create" class="btn btn-sm btn-primary">
                                    Create Rate Plan
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Plan Code</th>
                                            <th>Plan Name</th>
                                            <th>Room Type</th>
                                            <th>Season</th>
                                            <th class="text-end">Base Rate</th>
                                            <th class="text-end">Adjustment</th>
                                            <th>Min Nights</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_plans as $plan): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo escape_html($plan['plan_code'] ?? ''); ?></strong>
                                            </td>
                                            <td><?php echo escape_html($plan['plan_name'] ?? ''); ?></td>
                                            <td><?php echo escape_html($plan['type_name'] ?? ''); ?></td>
                                            <td>
                                                <?php echo !empty($plan['season_name']) ? escape_html($plan['season_name']) : '<span class="text-muted">All Year</span>'; ?>
                                            </td>
                                            <td class="text-end"><?php echo format_currency($plan['base_rate'] ?? 0); ?></td>
                                            <td class="text-end">
                                                <?php if (($plan['adjustment_type'] ?? '') == 'percentage'): ?>
                                                    <?php echo $plan['adjustment_value'] ?? 0; ?>%
                                                <?php else: ?>
                                                    <?php echo format_currency($plan['adjustment_value'] ?? 0); ?>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center"><?php echo $plan['min_nights'] ?? 1; ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo !empty($plan['is_active']) ? 'success' : 'secondary'; ?>">
                                                    <?php echo !empty($plan['is_active']) ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="rate-plans.php?edit=<?php echo $plan['rate_plan_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rate Management Tips -->
        <div class="row">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-lightbulb me-1"></i>
                            Rate Management Tips
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-info">
                                        <i class="fas fa-calendar-alt"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Seasons</span>
                                        <span class="info-box-number">Define peak/off-peak periods</span>
                                        <small>Create seasons to automatically adjust base rates</small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-success">
                                        <i class="fas fa-tags"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Rate Plans</span>
                                        <span class="info-box-number">Different packages for same room</span>
                                        <small>Create multiple rate plans per room type</small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-warning">
                                        <i class="fas fa-cogs"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Price Rules</span>
                                        <span class="info-box-number">Dynamic pricing adjustments</span>
                                        <small>Set rules for specific days or conditions</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-4 { margin-bottom: 1.5rem; }
.text-end { text-align: right; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
</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>';
}
?>