<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Cleaning Schedule
 * Developer: JOACHIM'S INNOTECH
 */

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

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

// Set page title
$page_title = 'Cleaning Schedule';

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

// Get date from request
$date = $_GET['date'] ?? date('Y-m-d');

// Get cleaning tasks for the selected date
$tasks = db_fetch_all("
    SELECT 
        t.*,
        r.room_number, rt.type_name,
        u.first_name, u.last_name,
        CASE 
            WHEN r.housekeeping_status = 'clean' THEN 'Clean'
            WHEN r.housekeeping_status = 'dirty' THEN 'Dirty'
            WHEN r.housekeeping_status = 'inspected' THEN 'Inspected'
            ELSE r.housekeeping_status
        END as room_status_display
    FROM hk_tasks t
    JOIN rooms r ON t.room_id = r.room_id
    JOIN room_types rt ON r.room_type_id = rt.room_type_id
    LEFT JOIN users u ON t.assigned_to = u.user_id
    WHERE DATE(t.created_at) = ? OR DATE(t.completed_at) = ?
    ORDER BY 
        CASE t.priority 
            WHEN 'urgent' THEN 1
            WHEN 'high' THEN 2
            WHEN 'medium' THEN 3
            WHEN 'low' THEN 4
        END,
        t.created_at
", [$date, $date]);

// Get rooms by floor for the visual schedule
$rooms_by_floor = db_fetch_all("
    SELECT 
        r.room_id, r.room_number, r.floor,
        r.housekeeping_status,
        rt.type_name,
        t.task_id, t.priority, t.status as task_status,
        u.first_name, u.last_name
    FROM rooms r
    JOIN room_types rt ON r.room_type_id = rt.room_type_id
    LEFT JOIN hk_tasks t ON r.room_id = t.room_id 
        AND DATE(t.created_at) = ? 
        AND t.status != 'completed'
    LEFT JOIN users u ON t.assigned_to = u.user_id
    WHERE r.is_active = 1
    ORDER BY r.floor, r.room_number
", [$date]);

// Group rooms by floor
$floors = [];
foreach ($rooms_by_floor as $room) {
    $floor = $room['floor'] ?: 'Ground';
    if (!isset($floors[$floor])) {
        $floors[$floor] = [];
    }
    $floors[$floor][] = $room;
}

// Get staff availability
$staff_availability = db_fetch_all("
    SELECT 
        u.user_id, u.first_name, u.last_name,
        COUNT(t.task_id) as assigned_tasks,
        GROUP_CONCAT(t.task_id) as task_ids
    FROM users u
    LEFT JOIN hk_tasks t ON u.user_id = t.assigned_to 
        AND DATE(t.created_at) = ? 
        AND t.status IN ('assigned', 'in_progress')
    WHERE u.role_id IN (7, 8) AND u.is_active = 1
    GROUP BY u.user_id
    ORDER BY u.first_name
", [$date]);

// Get statistics
$stats = [
    'total_tasks' => count($tasks),
    'pending' => db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE DATE(created_at) = ? AND status = 'pending'", [$date]),
    'assigned' => db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE DATE(created_at) = ? AND status = 'assigned'", [$date]),
    'in_progress' => db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE DATE(created_at) = ? AND status = 'in_progress'", [$date]),
    'completed' => db_fetch_value("SELECT COUNT(*) FROM hk_tasks WHERE DATE(completed_at) = ? AND status = 'completed'", [$date])
];

// Include header
require_once dirname(__DIR__, 3) . '/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">Cleaning Schedule</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="<?php echo base_url('housekeeping/dashboard.php'); ?>">Housekeeping</a></li>
                    <li class="breadcrumb-item"><a href="../tasks/index.php">Tasks</a></li>
                    <li class="breadcrumb-item active">Schedule</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Date Navigation -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-md-4">
                                <div class="btn-group">
                                    <a href="?date=<?php echo date('Y-m-d', strtotime($date . ' -1 day')); ?>" class="btn btn-primary">
                                        <i class="fas fa-chevron-left"></i> Previous Day
                                    </a>
                                    <a href="?date=<?php echo date('Y-m-d'); ?>" class="btn btn-info">
                                        <i class="fas fa-calendar-day"></i> Today
                                    </a>
                                    <a href="?date=<?php echo date('Y-m-d', strtotime($date . ' +1 day')); ?>" class="btn btn-primary">
                                        Next Day <i class="fas fa-chevron-right"></i>
                                    </a>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <form method="GET" class="form-inline justify-content-center">
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                                        </div>
                                        <input type="date" class="form-control" name="date" value="<?php echo $date; ?>">
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-primary">Go</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            
                            <div class="col-md-4 text-right">
                                <h4><?php echo format_date($date, 'l, F j, Y'); ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
            </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 $stats['total_tasks']; ?></h3>
                        <p>Total Tasks</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-tasks"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['pending']; ?></h3>
                        <p>Pending</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo $stats['assigned']; ?></h3>
                        <p>Assigned</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-user-check"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['in_progress']; ?></h3>
                        <p>In Progress</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-spinner"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['completed']; ?></h3>
                        <p>Completed</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php 
                            $efficiency = $stats['total_tasks'] > 0 
                                ? round(($stats['completed'] / $stats['total_tasks']) * 100, 1) 
                                : 0;
                            echo $efficiency; ?>%
                        </h3>
                        <p>Efficiency</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Staff Availability -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-users mr-1"></i>
                            Staff Availability
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php foreach ($staff_availability as $staff): ?>
                            <div class="col-md-3 col-sm-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-<?php 
                                        echo $staff['assigned_tasks'] >= 5 ? 'danger' : 
                                            ($staff['assigned_tasks'] >= 3 ? 'warning' : 'success');
                                    ?> elevation-1">
                                        <i class="fas fa-user"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text"><?php echo $staff['first_name']; ?></span>
                                        <span class="info-box-number"><?php echo $staff['assigned_tasks']; ?> active tasks</span>
                                        <div class="progress">
                                            <?php $load = min(100, ($staff['assigned_tasks'] / 5) * 100); ?>
                                            <div class="progress-bar bg-<?php 
                                                echo $load >= 80 ? 'danger' : ($load >= 50 ? 'warning' : 'success');
                                            ?>" style="width: <?php echo $load; ?>%"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Room Grid Schedule -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-th-large mr-1"></i>
                            Room Cleaning Schedule
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" onclick="refreshSchedule()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body">
                        <?php foreach ($floors as $floor => $rooms): ?>
                        <div class="floor-section mb-4">
                            <h4 class="bg-light p-2 mb-3">
                                <i class="fas fa-layer-group mr-2"></i>
                                Floor <?php echo $floor; ?>
                            </h4>
                            
                            <div class="room-grid">
                                <?php foreach ($rooms as $room): ?>
                                <div class="room-schedule-item" 
                                     onclick="showRoomDetails(<?php echo $room['room_id']; ?>)"
                                     data-toggle="tooltip" 
                                     title="<?php echo $room['type_name']; ?>">
                                    
                                    <div class="room-number"><?php echo $room['room_number']; ?></div>
                                    
                                    <div class="room-status">
                                        <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($room['housekeeping_status']); ?>
                                        </span>
                                    </div>
                                    
                                    <?php if ($room['task_id']): ?>
                                    <div class="task-info">
                                        <span class="badge badge-<?php 
                                            echo $room['priority'] == 'urgent' ? 'danger' : 
                                                ($room['priority'] == 'high' ? 'warning' : 'info');
                                        ?>">
                                            <?php echo ucfirst($room['priority']); ?>
                                        </span>
                                        <br>
                                        <small class="text-muted">
                                            <?php echo $room['first_name'] ?: 'Unassigned'; ?>
                                        </small>
                                    </div>
                                    <?php else: ?>
                                    <div class="no-task">
                                        <small class="text-muted">No task</small>
                                        <br>
                                        <a href="../tasks/create.php?room_id=<?php echo $room['room_id']; ?>" 
                                           class="btn btn-sm btn-success mt-1">
                                            <i class="fas fa-plus"></i>
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Today's Tasks List -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list mr-1"></i>
                            Today's Cleaning Tasks
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($tasks)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-broom fa-3x mb-3"></i>
                                <p>No cleaning tasks scheduled for this day</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Time</th>
                                            <th>Task #</th>
                                            <th>Room</th>
                                            <th>Task Type</th>
                                            <th>Priority</th>
                                            <th>Status</th>
                                            <th>Assigned To</th>
                                            <th>Room Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($tasks as $task): ?>
                                        <tr>
                                            <td>
                                                <?php echo date('H:i', strtotime($task['created_at'])); ?>
                                            </td>
                                            <td>
                                                <strong><?php echo $task['task_code']; ?></strong>
                                            </td>
                                            <td>
                                                <a href="<?php echo base_url('rooms/rooms/view.php?id=' . $task['room_id']); ?>">
                                                    Room <?php echo $task['room_number']; ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php 
                                                $task_types = unserialize(TASK_TYPES);
                                                echo $task_types[$task['task_type']] ?? ucfirst($task['task_type']);
                                                ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $task['priority'] == 'urgent' ? 'danger' : 
                                                        ($task['priority'] == 'high' ? 'warning' : 
                                                        ($task['priority'] == 'medium' ? 'info' : 'secondary'));
                                                ?>">
                                                    <?php echo ucfirst($task['priority']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $task['status'] == 'completed' ? 'success' : 
                                                        ($task['status'] == 'in_progress' ? 'primary' : 
                                                        ($task['status'] == 'assigned' ? 'info' : 'warning'));
                                                ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $task['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo $task['first_name'] ?: 'Unassigned'; ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $task['room_status_display'] == 'Clean' ? 'success' : 
                                                        ($task['room_status_display'] == 'Dirty' ? 'warning' : 
                                                        ($task['room_status_display'] == 'Inspected' ? 'info' : 'secondary'));
                                                ?>">
                                                    <?php echo $task['room_status_display']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($task['status'] != 'completed'): ?>
                                                    <a href="../tasks/complete.php?id=<?php echo $task['task_id']; ?>" 
                                                       class="btn btn-sm btn-success">
                                                        <i class="fas fa-check"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Room Details Modal -->
<div class="modal fade" id="roomDetailsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Room Details</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="roomDetailsContent">
                Loading...
            </div>
        </div>
    </div>
</div>

<script>
function showRoomDetails(roomId) {
    $('#roomDetailsModal').modal('show');
    $('#roomDetailsContent').html('<div class="text-center"><div class="spinner-border text-primary"></div></div>');
    
    $.get('<?php echo base_url('api/get-room.php'); ?>', { id: roomId }, function(response) {
        if (response.status === 'success') {
            displayRoomDetails(response.data);
        } else {
            $('#roomDetailsContent').html('<div class="alert alert-danger">Failed to load room details</div>');
        }
    });
}

function displayRoomDetails(room) {
    let html = `
        <h4>Room ${room.room_number}</h4>
        <p><strong>Type:</strong> ${room.type_name}</p>
        <p><strong>Floor:</strong> ${room.floor || 'N/A'}</p>
        <p><strong>Status:</strong> <span class="badge badge-${getStatusBadge(room.status)}">${room.status}</span></p>
        <p><strong>Housekeeping:</strong> <span class="badge badge-${getHKStatusBadge(room.housekeeping_status)}">${room.housekeeping_status}</span></p>
        <hr>
        <div class="text-right">
            <a href="../tasks/create.php?room_id=${room.room_id}" class="btn btn-sm btn-primary">Create Task</a>
            <a href="<?php echo base_url('rooms/rooms/view.php?id='); ?>${room.room_id}" class="btn btn-sm btn-info">View Room</a>
        </div>
    `;
    
    $('#roomDetailsContent').html(html);
}

function getStatusBadge(status) {
    switch(status) {
        case 'available': return 'success';
        case 'occupied': return 'danger';
        case 'maintenance': return 'warning';
        case 'housekeeping': return 'info';
        default: return 'secondary';
    }
}

function getHKStatusBadge(status) {
    switch(status) {
        case 'clean': return 'success';
        case 'dirty': return 'warning';
        case 'inspected': return 'info';
        case 'out_of_service': return 'danger';
        default: return 'secondary';
    }
}

function refreshSchedule() {
    location.reload();
}
</script>

<style>
.room-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 10px;
    margin-bottom: 20px;
}

.room-schedule-item {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 12px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.room-schedule-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    border-color: #007bff;
}

.room-schedule-item .room-number {
    font-size: 1.2rem;
    font-weight: 600;
    margin-bottom: 5px;
}

.room-schedule-item .room-status {
    margin-bottom: 8px;
}

.room-schedule-item .task-info {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px dashed #dee2e6;
}

.room-schedule-item .no-task {
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px dashed #dee2e6;
}

.floor-section {
    margin-bottom: 30px;
}

.floor-section h4 {
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 15px;
}
</style>

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