<?php
/**
 * Housekeeping Controller
 * Manage cleaning tasks
 */

class HousekeepingController {
    private $db;
    private $config;

    public function __construct($db, $config) {
        $this->db = $db;
        $this->config = $config;
    }

    public function getTasks($filters = []) {
        try {
            $query = "
                SELECT h.*, 
                       b.booking_reference, b.check_in, b.check_out,
                       p.name as property_name,
                       r.name as room_name,
                       u.name as assigned_to_name
                FROM housekeeping_tasks h
                LEFT JOIN bookings b ON h.booking_id = b.id
                LEFT JOIN properties p ON h.property_id = p.id
                LEFT JOIN rooms r ON b.room_id = r.id
                LEFT JOIN users u ON h.assigned_to = u.id
                WHERE 1=1
            ";
            $params = [];

            if (!empty($filters['property_id'])) {
                $query .= " AND h.property_id = ?";
                $params[] = $filters['property_id'];
            }
            if (!empty($filters['status'])) {
                $query .= " AND h.status = ?";
                $params[] = $filters['status'];
            }
            if (!empty($filters['assigned_to'])) {
                $query .= " AND h.assigned_to = ?";
                $params[] = $filters['assigned_to'];
            }

            $query .= " ORDER BY h.scheduled_date ASC";

            $stmt = $this->db->prepare($query);
            $stmt->execute($params);
            $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return ['success' => true, 'tasks' => $tasks, 'count' => count($tasks)];
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error fetching tasks'];
        }
    }

    public function createTask($data) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO housekeeping_tasks 
                (booking_id, property_id, task_type, scheduled_date, assigned_to, notes, status, created_at)
                VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())
            ");
            $stmt->execute([
                $data['booking_id'] ?? null,
                $data['property_id'],
                $data['task_type'] ?? 'cleaning',
                $data['scheduled_date'],
                $data['assigned_to'] ?? null,
                $data['notes'] ?? null
            ]);
            return ['success' => true, 'task_id' => $this->db->lastInsertId()];
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error creating task'];
        }
    }

    public function updateStatus($task_id, $status, $notes = null) {
        try {
            $stmt = $this->db->prepare("
                UPDATE housekeeping_tasks 
                SET status = ?, notes = COALESCE(?, notes), 
                    completed_at = CASE WHEN ? = 'completed' THEN NOW() ELSE completed_at END
                WHERE id = ?
            ");
            $stmt->execute([$status, $notes, $status, $task_id]);
            return ['success' => true, 'message' => 'Task updated'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error updating task'];
        }
    }

    public function assignTask($task_id, $user_id) {
        try {
            $stmt = $this->db->prepare("UPDATE housekeeping_tasks SET assigned_to = ? WHERE id = ?");
            $stmt->execute([$user_id, $task_id]);
            return ['success' => true, 'message' => 'Task assigned'];
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error assigning task'];
        }
    }
}
