<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Room Status Report
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('reports.view');

// Set page title
$page_title = 'Room Status Report';

// Get current user
$current_user = current_user();

// Get report parameters
$date = $_GET['date'] ?? date('Y-m-d');
$floor = $_GET['floor'] ?? '';
$room_type_id = isset($_GET['room_type_id']) && $_GET['room_type_id'] !== '' ? (int)$_GET['room_type_id'] : null;
$status = $_GET['status'] ?? '';
$hk_status = $_GET['hk_status'] ?? '';
$export = $_GET['export'] ?? '';

// Get room types for filter
$room_types = db_fetch_all("SELECT room_type_id, type_name FROM room_types ORDER BY type_name");

// Get floors for filter
$floors = db_fetch_all("SELECT DISTINCT floor FROM rooms WHERE floor IS NOT NULL ORDER BY floor");

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

if (!empty($floor)) {
    $where .= " AND r.floor = ?";
    $params[] = $floor;
}

if ($room_type_id) {
    $where .= " AND r.room_type_id = ?";
    $params[] = $room_type_id;
}

if (!empty($status)) {
    $where .= " AND r.status = ?";
    $params[] = $status;
}

if (!empty($hk_status)) {
    $where .= " AND r.housekeeping_status = ?";
    $params[] = $hk_status;
}

// Get room status data
$rooms = db_fetch_all("
    SELECT 
        r.*,
        rt.type_name,
        CONCAT(g.first_name, ' ', g.last_name) as guest_name,
        res.reservation_id, res.booking_code,
        res.check_in_date, res.check_out_date,
        DATEDIFF(res.check_out_date, CURDATE()) as days_remaining,
        t.task_id, t.priority as task_priority,
        u.first_name as assigned_first
    FROM rooms r
    JOIN room_types rt ON r.room_type_id = rt.room_type_id
    LEFT JOIN reservations res ON r.room_id = res.room_id 
        AND res.booking_status = 'checked_in'
    LEFT JOIN guests g ON res.guest_id = g.guest_id
    LEFT JOIN hk_tasks t ON r.room_id = t.room_id 
        AND t.status IN ('pending', 'assigned', 'in_progress')
    LEFT JOIN users u ON t.assigned_to = u.user_id
    WHERE $where
    ORDER BY r.floor, r.room_number
", $params);

// Calculate summary statistics
$summary = [
    'total_rooms' => count($rooms),
    'available' => 0,
    'occupied' => 0,
    'maintenance' => 0,
    'housekeeping' => 0,
    'blocked' => 0,
    'clean' => 0,
    'dirty' => 0,
    'inspected' => 0,
    'out_of_service' => 0,
    'checkout_today' => 0,
    'vacant_clean' => 0,
    'vacant_dirty' => 0,
    'occupied_clean' => 0,
    'occupied_dirty' => 0
];

foreach ($rooms as $room) {
    // Count by status
    switch ($room['status']) {
        case 'available': $summary['available']++; break;
        case 'occupied': $summary['occupied']++; break;
        case 'maintenance': $summary['maintenance']++; break;
        case 'housekeeping': $summary['housekeeping']++; break;
        case 'blocked': $summary['blocked']++; break;
    }
    
    // Count by housekeeping status
    switch ($room['housekeeping_status']) {
        case 'clean': $summary['clean']++; break;
        case 'dirty': $summary['dirty']++; break;
        case 'inspected': $summary['inspected']++; break;
        case 'out_of_service': $summary['out_of_service']++; break;
    }
    
    // Combined statuses
    if ($room['status'] == 'available' && $room['housekeeping_status'] == 'clean') {
        $summary['vacant_clean']++;
    }
    if ($room['status'] == 'available' && $room['housekeeping_status'] == 'dirty') {
        $summary['vacant_dirty']++;
    }
    if ($room['status'] == 'occupied' && $room['housekeeping_status'] == 'clean') {
        $summary['occupied_clean']++;
    }
    if ($room['status'] == 'occupied' && $room['housekeeping_status'] == 'dirty') {
        $summary['occupied_dirty']++;
    }
    
    // Checkouts today
    if ($room['check_out_date'] == $date) {
        $summary['checkout_today']++;
    }
}

// Handle export
if ($export === 'pdf') {
    export_pdf($summary, $rooms, $date);
} elseif ($export === 'excel') {
    export_excel($summary, $rooms, $date);
} elseif ($export === 'csv') {
    export_csv($summary, $rooms, $date);
}

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.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 Status Report</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="dashboard.php">Reports</a></li>
                    <li class="breadcrumb-item active">Room Status</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Report Controls -->
        <div class="card">
            <div class="card-body">
                <form method="GET" class="form-inline">
                    <div class="form-group mb-2 mr-2">
                        <label for="date" class="mr-2">Date:</label>
                        <input type="date" class="form-control" id="date" name="date" 
                               value="<?php echo $date; ?>">
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="floor" class="mr-2">Floor:</label>
                        <select class="form-control" id="floor" name="floor">
                            <option value="">All Floors</option>
                            <?php foreach ($floors as $f): ?>
                                <option value="<?php echo $f['floor']; ?>" 
                                        <?php echo $floor == $f['floor'] ? 'selected' : ''; ?>>
                                    Floor <?php echo $f['floor']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="room_type_id" class="mr-2">Room Type:</label>
                        <select class="form-control" id="room_type_id" name="room_type_id">
                            <option value="">All Types</option>
                            <?php foreach ($room_types as $type): ?>
                                <option value="<?php echo $type['room_type_id']; ?>" 
                                        <?php echo $room_type_id == $type['room_type_id'] ? 'selected' : ''; ?>>
                                    <?php echo $type['type_name']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="status" class="mr-2">Room Status:</label>
                        <select class="form-control" id="status" name="status">
                            <option value="">All</option>
                            <option value="available" <?php echo $status == 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="occupied" <?php echo $status == 'occupied' ? 'selected' : ''; ?>>Occupied</option>
                            <option value="maintenance" <?php echo $status == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                            <option value="housekeeping" <?php echo $status == 'housekeeping' ? 'selected' : ''; ?>>Housekeeping</option>
                            <option value="blocked" <?php echo $status == 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                        </select>
                    </div>
                    
                    <div class="form-group mb-2 mr-2">
                        <label for="hk_status" class="mr-2">HK Status:</label>
                        <select class="form-control" id="hk_status" name="hk_status">
                            <option value="">All</option>
                            <option value="clean" <?php echo $hk_status == 'clean' ? 'selected' : ''; ?>>Clean</option>
                            <option value="dirty" <?php echo $hk_status == 'dirty' ? 'selected' : ''; ?>>Dirty</option>
                            <option value="inspected" <?php echo $hk_status == 'inspected' ? 'selected' : ''; ?>>Inspected</option>
                            <option value="out_of_service" <?php echo $hk_status == 'out_of_service' ? 'selected' : ''; ?>>Out of Service</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn btn-primary mb-2 mr-2">
                        <i class="fas fa-sync-alt"></i> Generate
                    </button>
                    
                    <button type="button" class="btn btn-success mb-2 mr-2" onclick="exportReport('pdf')">
                        <i class="fas fa-file-pdf"></i> PDF
                    </button>
                    
                    <button type="button" class="btn btn-info mb-2 mr-2" onclick="exportReport('excel')">
                        <i class="fas fa-file-excel"></i> Excel
                    </button>
                    
                    <button type="button" class="btn btn-secondary mb-2" onclick="exportReport('csv')">
                        <i class="fas fa-file-csv"></i> CSV
                    </button>
                </form>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $summary['total_rooms']; ?></h3>
                        <p>Total Rooms</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-hotel"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $summary['available']; ?></h3>
                        <p>Available</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-door-open"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $summary['occupied']; ?></h3>
                        <p>Occupied</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-warning">
                    <div class="inner">
                        <h3><?php echo $summary['maintenance']; ?></h3>
                        <p>Maintenance</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tools"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo $summary['housekeeping']; ?></h3>
                        <p>Housekeeping</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-broom"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo $summary['blocked']; ?></h3>
                        <p>Blocked</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-ban"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Status Summary -->
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie mr-1"></i>
                            Room Status Distribution
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="statusChart" style="height: 250px;"></canvas>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie mr-1"></i>
                            Housekeeping Status
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="hkChart" style="height: 250px;"></canvas>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle mr-1"></i>
                            Ready for Occupancy
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Vacant & Clean:</th>
                                <td class="text-right">
                                    <span class="badge badge-success"><?php echo $summary['vacant_clean']; ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th>Vacant & Dirty:</th>
                                <td class="text-right">
                                    <span class="badge badge-warning"><?php echo $summary['vacant_dirty']; ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th>Occupied & Clean:</th>
                                <td class="text-right">
                                    <span class="badge badge-info"><?php echo $summary['occupied_clean']; ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th>Occupied & Dirty:</th>
                                <td class="text-right">
                                    <span class="badge badge-secondary"><?php echo $summary['occupied_dirty']; ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th>Checkouts Today:</th>
                                <td class="text-right">
                                    <span class="badge badge-warning"><?php echo $summary['checkout_today']; ?></span>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Room Status Table -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-table mr-1"></i>
                            Room Status Details
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Room</th>
                                        <th>Floor</th>
                                        <th>Type</th>
                                        <th>Room Status</th>
                                        <th>HK Status</th>
                                        <th>Guest</th>
                                        <th>Check-out</th>
                                        <th>Days Left</th>
                                        <th>Tasks</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rooms as $room): ?>
                                    <tr class="<?php 
                                        echo $room['status'] == 'maintenance' ? 'table-danger' : 
                                            ($room['status'] == 'occupied' ? 'table-success' : 
                                            ($room['status'] == 'housekeeping' ? 'table-warning' : ''));
                                    ?>">
                                        <td>
                                            <strong><?php echo $room['room_number']; ?></strong>
                                        </td>
                                        <td><?php echo $room['floor'] ?: '-'; ?></td>
                                        <td><?php echo $room['type_name']; ?></td>
                                        <td>
                                            <span class="badge badge-<?php 
                                                echo $room['status'] == 'available' ? 'success' : 
                                                    ($room['status'] == 'occupied' ? 'danger' : 
                                                    ($room['status'] == 'maintenance' ? 'warning' : 
                                                    ($room['status'] == 'housekeeping' ? 'info' : 'secondary')));
                                            ?>">
                                                <?php echo ucfirst($room['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge badge-<?php 
                                                echo $room['housekeeping_status'] == 'clean' ? 'success' : 
                                                    ($room['housekeeping_status'] == 'dirty' ? 'warning' : 
                                                    ($room['housekeeping_status'] == 'inspected' ? 'info' : 'secondary'));
                                            ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $room['housekeeping_status'])); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($room['guest_name']): ?>
                                                <a href="<?php echo base_url('guests/view.php?id=' . $room['guest_id']); ?>">
                                                    <?php echo escape_html($room['guest_name']); ?>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php echo $room['check_out_date'] ? format_date($room['check_out_date']) : '-'; ?>
                                        </td>
                                        <td>
                                            <?php if ($room['days_remaining'] !== null): ?>
                                                <?php if ($room['days_remaining'] > 0): ?>
                                                    <span class="badge badge-info"><?php echo $room['days_remaining']; ?> days</span>
                                                <?php elseif ($room['days_remaining'] == 0): ?>
                                                    <span class="badge badge-warning">Today</span>
                                                <?php else: ?>
                                                    <span class="badge badge-danger">Overdue</span>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                -
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($room['task_id']): ?>
                                                <span class="badge badge-<?php 
                                                    echo $room['task_priority'] == 'urgent' ? 'danger' : 
                                                        ($room['task_priority'] == 'high' ? 'warning' : 'info');
                                                ?>">
                                                    <i class="fas fa-broom"></i>
                                                    <?php echo $room['assigned_first'] ?: 'Pending'; ?>
                                                </span>
                                            <?php else: ?>
                                                -
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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

<script>
$(document).ready(function() {
    // Status Chart
    const statusCtx = document.getElementById('statusChart').getContext('2d');
    
    new Chart(statusCtx, {
        type: 'doughnut',
        data: {
            labels: ['Available', 'Occupied', 'Maintenance', 'Housekeeping', 'Blocked'],
            datasets: [{
                data: [
                    <?php echo $summary['available']; ?>,
                    <?php echo $summary['occupied']; ?>,
                    <?php echo $summary['maintenance']; ?>,
                    <?php echo $summary['housekeeping']; ?>,
                    <?php echo $summary['blocked']; ?>
                ],
                backgroundColor: ['#28a745', '#dc3545', '#ffc107', '#17a2b8', '#6c757d'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // Housekeeping Chart
    const hkCtx = document.getElementById('hkChart').getContext('2d');
    
    new Chart(hkCtx, {
        type: 'doughnut',
        data: {
            labels: ['Clean', 'Dirty', 'Inspected', 'Out of Service'],
            datasets: [{
                data: [
                    <?php echo $summary['clean']; ?>,
                    <?php echo $summary['dirty']; ?>,
                    <?php echo $summary['inspected']; ?>,
                    <?php echo $summary['out_of_service']; ?>
                ],
                backgroundColor: ['#28a745', '#ffc107', '#17a2b8', '#6c757d'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
});

function exportReport(format) {
    const url = new URL(window.location.href);
    url.searchParams.set('export', format);
    window.location.href = url.toString();
}
</script>

<?php
/**
 * Export as PDF
 */
function export_pdf($summary, $rooms, $date) {
    header('Location: export-pdf.php?report=room_status&date=' . $date);
    exit;
}

/**
 * Export as Excel
 */
function export_excel($summary, $rooms, $date) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="room_status_report_' . $date . '.xls"');
    
    echo "Room Status Report\n";
    echo "Date: " . format_date($date) . "\n\n";
    
    echo "Summary\n";
    echo "Total Rooms\t" . $summary['total_rooms'] . "\n";
    echo "Available\t" . $summary['available'] . "\n";
    echo "Occupied\t" . $summary['occupied'] . "\n";
    echo "Maintenance\t" . $summary['maintenance'] . "\n";
    echo "Housekeeping\t" . $summary['housekeeping'] . "\n";
    echo "Blocked\t" . $summary['blocked'] . "\n";
    echo "Clean\t" . $summary['clean'] . "\n";
    echo "Dirty\t" . $summary['dirty'] . "\n";
    echo "Inspected\t" . $summary['inspected'] . "\n";
    echo "Out of Service\t" . $summary['out_of_service'] . "\n";
    echo "Checkouts Today\t" . $summary['checkout_today'] . "\n\n";
    
    echo "Room Details\n";
    echo "Room\tFloor\tType\tRoom Status\tHK Status\tGuest\tCheck-out\tDays Left\n";
    
    foreach ($rooms as $room) {
        $guest = $room['guest_name'] ?: '-';
        $checkout = $room['check_out_date'] ?: '-';
        $days_left = $room['days_remaining'] ?? '-';
        
        echo $room['room_number'] . "\t";
        echo ($room['floor'] ?: '-') . "\t";
        echo $room['type_name'] . "\t";
        echo $room['status'] . "\t";
        echo $room['housekeeping_status'] . "\t";
        echo $guest . "\t";
        echo $checkout . "\t";
        echo $days_left . "\n";
    }
    
    exit;
}

/**
 * Export as CSV
 */
function export_csv($summary, $rooms, $date) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="room_status_report_' . $date . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    fputcsv($output, ['Room Status Report']);
    fputcsv($output, ['Date:', format_date($date)]);
    fputcsv($output, []);
    
    fputcsv($output, ['Summary']);
    fputcsv($output, ['Total Rooms', $summary['total_rooms']]);
    fputcsv($output, ['Available', $summary['available']]);
    fputcsv($output, ['Occupied', $summary['occupied']]);
    fputcsv($output, ['Maintenance', $summary['maintenance']]);
    fputcsv($output, ['Housekeeping', $summary['housekeeping']]);
    fputcsv($output, ['Blocked', $summary['blocked']]);
    fputcsv($output, ['Clean', $summary['clean']]);
    fputcsv($output, ['Dirty', $summary['dirty']]);
    fputcsv($output, ['Inspected', $summary['inspected']]);
    fputcsv($output, ['Out of Service', $summary['out_of_service']]);
    fputcsv($output, ['Checkouts Today', $summary['checkout_today']]);
    fputcsv($output, []);
    
    fputcsv($output, ['Room', 'Floor', 'Type', 'Room Status', 'HK Status', 'Guest', 'Check-out', 'Days Left']);
    foreach ($rooms as $room) {
        fputcsv($output, [
            $room['room_number'],
            $room['floor'] ?: '-',
            $room['type_name'],
            $room['status'],
            $room['housekeeping_status'],
            $room['guest_name'] ?: '-',
            $room['check_out_date'] ?: '-',
            $room['days_remaining'] ?? '-'
        ]);
    }
    
    fclose($output);
    exit;
}

// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>