<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Room Types Management - List View - 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/room-types/index.php
// Need to go up to: /HMSPOS/
$base_path = null;

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

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/room-types/ -> /HMSPOS/
    $base_path = 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 helper functions if they don't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('truncate_text')) {
    function truncate_text($text, $length = 50) {
        if (strlen($text) <= $length) return $text;
        return substr($text, 0, $length) . '...';
    }
}

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

// Set page title
$page_title = 'Room Types 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;
    }
}

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

// Build where clause
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (type_name LIKE ? OR type_code LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
}

// Validate sort column
$allowed_sort = ['room_type_id', 'type_code', 'type_name', 'base_price', 'max_adults', 'max_occupancy'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'type_name';
}

// Get total count
$total = 0;
try {
    $count_sql = "SELECT COUNT(*) FROM room_types WHERE $where";
    $total = (int)db_fetch_value($count_sql, $params) ?: 0;
} catch (Exception $e) {
    error_log("Error counting room types: " . $e->getMessage());
}

// Get room types with statistics
$room_types = [];
try {
    $sql = "
        SELECT 
            rt.*,
            COUNT(r.room_id) as total_rooms,
            SUM(CASE WHEN r.status = 'occupied' THEN 1 ELSE 0 END) as occupied_rooms,
            rt.base_price as current_rate,
            (SELECT COUNT(*) FROM rate_plans WHERE room_type_id = rt.room_type_id AND is_active = 1) as rate_plans_count
        FROM room_types rt
        LEFT JOIN rooms r ON rt.room_type_id = r.room_type_id AND r.is_active = 1
        WHERE $where
        GROUP BY rt.room_type_id
        ORDER BY $sort $order
    ";
    
    // Get paginated data
    $offset = ($page - 1) * $per_page;
    $data_sql = $sql . " LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
    $room_types = db_fetch_all($data_sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
    $room_types = [];
}

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

// 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>Room Types 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; }
        </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="#">Room Types 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">Room Types 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">Room Types</li>
                </ol>
            </div>
        </div>
    </div>
</div>

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

        <!-- Filters and Actions -->
        <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-8">
                        <input type="text" class="form-control" name="search" placeholder="Search room types..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-1"></i> Apply Filters
                        </button>
                        
                        <a href="?" class="btn btn-secondary">
                            <i class="fas fa-times me-1"></i> Clear
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Room Types Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-tags me-1"></i>
                    Room Types (<?php echo $total; ?> total)
                </h3>
                <div class="card-tools">
                    <?php if (function_exists('has_permission') && has_permission('roomtypes.create')): ?>
                        <a href="create.php" class="btn btn-sm btn-primary">
                            <i class="fas fa-plus"></i> New Room Type
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($room_types)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-tag fa-4x mb-3"></i>
                        <h5>No room types found</h5>
                        <p>Create your first room type to get started</p>
                        <?php if (function_exists('has_permission') && has_permission('roomtypes.create')): ?>
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i> Create Room Type
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>
                                        <a href="?sort=type_code&order=<?php echo $sort === 'type_code' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>" class="text-dark">
                                            Code
                                            <?php if ($sort === 'type_code'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>
                                        <a href="?sort=type_name&order=<?php echo $sort === 'type_name' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>" class="text-dark">
                                            Name
                                            <?php if ($sort === 'type_name'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th class="text-center">Capacity</th>
                                    <th class="text-end">
                                        <a href="?sort=base_price&order=<?php echo $sort === 'base_price' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>" class="text-dark">
                                            Base Price
                                            <?php if ($sort === 'base_price'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th class="text-center">Rooms</th>
                                    <th class="text-center">Occupied</th>
                                    <th class="text-center">Rate Plans</th>
                                    <th width="120">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($room_types as $type): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo escape_html($type['type_code'] ?? ''); ?></strong>
                                    </td>
                                    <td>
                                        <a href="view.php?id=<?php echo $type['room_type_id'] ?? 0; ?>">
                                            <?php echo escape_html($type['type_name'] ?? ''); ?>
                                        </a>
                                    </td>
                                    <td class="text-center">
                                        <i class="fas fa-user me-1"></i> <?php echo $type['max_adults'] ?? 2; ?> 
                                        <i class="fas fa-child ms-2 me-1"></i> <?php echo $type['max_children'] ?? 0; ?>
                                        <br>
                                        <small class="text-muted">Max: <?php echo $type['max_occupancy'] ?? 2; ?></small>
                                    </td>
                                    <td class="text-end">
                                        <strong><?php echo format_currency($type['base_price'] ?? 0); ?></strong>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $type['total_rooms'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-center">
                                        <?php 
                                        $total_rooms = $type['total_rooms'] ?? 0;
                                        $occupied = $type['occupied_rooms'] ?? 0;
                                        $occ_percent = $total_rooms > 0 ? round(($occupied / $total_rooms) * 100) : 0;
                                        ?>
                                        <div class="progress progress-xs">
                                            <div class="progress-bar bg-<?php echo $occ_percent > 80 ? 'success' : ($occ_percent > 50 ? 'warning' : 'danger'); ?>" 
                                                 style="width: <?php echo $occ_percent; ?>%"></div>
                                        </div>
                                        <small><?php echo $occupied; ?>/<?php echo $total_rooms; ?></small>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-secondary"><?php echo $type['rate_plans_count'] ?? 0; ?></span>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="view.php?id=<?php echo $type['room_type_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('roomtypes.edit')): ?>
                                                <a href="edit.php?id=<?php echo $type['room_type_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('roomtypes.delete') && ($type['total_rooms'] ?? 0) == 0): ?>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteRoomType(<?php echo $type['room_type_id'] ?? 0; ?>, '<?php echo escape_html($type['type_name'] ?? ''); ?>')"
                                                        title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer clearfix">
                <ul class="pagination pagination-sm float-end">
                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=1&search=<?php echo urlencode($search); ?>&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); ?>&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); ?>&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); ?>&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); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Room Type</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete room type <strong id="deleteTypeName"></strong>?</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle me-1"></i> This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" action="delete.php" id="deleteForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="room_type_id" id="deleteTypeId">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function deleteRoomType(typeId, typeName) {
    document.getElementById('deleteTypeId').value = typeId;
    document.getElementById('deleteTypeName').textContent = typeName;
    
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}
</script>

<style>
.progress-xs {
    height: 5px;
    margin: 5px 0;
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.ms-2 { margin-left: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.text-end { text-align: right; }
.float-end { float: right; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; color: #fff; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; 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>';
}
?>