<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$id = (int)($d['id'] ?? 0);
$action = $d['action'] ?? null;

if ($method === 'GET' && $action === 'today') {
    require_permission('tickets.view');
    $today = date('Y-m-d');
    $pid = !empty($d['property_id']) ? (int)$d['property_id'] : null;
    $sql = "SELECT t.id, t.task_type, t.priority, t.status, t.scheduled_date,
                   t.started_at, t.completed_at, t.notes,
                   r.id AS room_id, r.room_number, r.floor, r.housekeeping_status,
                   rt.name AS room_type_name,
                   u.name AS assigned_to_name,
                   t.assigned_to
            FROM housekeeping_tasks t
            JOIN rooms r ON r.id = t.room_id
            JOIN room_types rt ON rt.id = r.room_type_id
            LEFT JOIN users u ON u.id = t.assigned_to
            WHERE t.scheduled_date = ?";
    $params = [$today];
    if ($pid) { $sql .= ' AND r.property_id = ?'; $params[] = $pid; }
    $sql .= " ORDER BY FIELD(t.priority,'urgent','high','normal','low'),
                       FIELD(t.status,'in_progress','pending','completed','skipped'),
                       r.room_number";
    $s = db()->prepare($sql); $s->execute($params);
    json_ok($s->fetchAll());
}

if ($method === 'GET') {
    require_permission('tickets.view');
    if ($id) {
        $s = db()->prepare("SELECT t.*, r.room_number, r.floor, rt.name AS room_type_name,
                   u.name AS assigned_to_name, c.name AS created_by_name
            FROM housekeeping_tasks t
            JOIN rooms r ON r.id = t.room_id
            JOIN room_types rt ON rt.id = r.room_type_id
            LEFT JOIN users u ON u.id = t.assigned_to
            LEFT JOIN users c ON c.id = t.created_by
            WHERE t.id = ?");
        $s->execute([$id]);
        $task = $s->fetch();
        if (!$task) json_error('Not found', 404);
        json_ok($task);
    }
    $where = ['1=1']; $params = [];
    if (!empty($d['status'])) { $where[] = 't.status = ?'; $params[] = (string)$d['status']; }
    if (!empty($d['assigned_to'])) { $where[] = 't.assigned_to = ?'; $params[] = (int)$d['assigned_to']; }
    if (!empty($d['from'])) { $where[] = 't.scheduled_date >= ?'; $params[] = $d['from']; }
    if (!empty($d['to'])) { $where[] = 't.scheduled_date <= ?'; $params[] = $d['to']; }
    if (!empty($d['property_id'])) { $where[] = 'r.property_id = ?'; $params[] = (int)$d['property_id']; }
    $sql = "SELECT t.id, t.task_type, t.priority, t.status, t.scheduled_date,
                   t.started_at, t.completed_at,
                   r.room_number, r.floor, rt.name AS room_type_name,
                   u.name AS assigned_to_name
            FROM housekeeping_tasks t
            JOIN rooms r ON r.id = t.room_id
            JOIN room_types rt ON rt.id = r.room_type_id
            LEFT JOIN users u ON u.id = t.assigned_to
            WHERE " . implode(' AND ', $where) . "
            ORDER BY t.scheduled_date DESC, FIELD(t.priority,'urgent','high','normal','low')
            LIMIT 200";
    $s = db()->prepare($sql); $s->execute($params);
    json_ok($s->fetchAll());
}

csrf_check();

if ($method === 'POST') {
    require_permission('tickets.manage');
    $errors = v_required($d, ['room_id','task_type','scheduled_date']);
    if ($errors) json_error('Validation failed', 422, $errors);
    db()->prepare('INSERT INTO housekeeping_tasks (room_id, task_type, priority, status, assigned_to, scheduled_date, notes, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)')->execute([
        (int)$d['room_id'],
        $d['task_type'],
        $d['priority'] ?? 'normal',
        $d['status'] ?? 'pending',
        !empty($d['assigned_to']) ? (int)$d['assigned_to'] : null,
        $d['scheduled_date'],
        $d['notes'] ?? null,
        current_user()['id']
    ]);
    $newId = (int)db()->lastInsertId();
    audit_log('housekeeping.create', 'task', $newId);
    json_ok(['id' => $newId], 'Task created');
}

if (($method === 'PUT' || $method === 'PATCH') && $action === 'start') {
    require_permission('tickets.manage');
    if (!$id) json_error('id required', 422);
    db()->prepare('UPDATE housekeeping_tasks SET status="in_progress", started_at=NOW(), assigned_to=? WHERE id=?')->execute([current_user()['id'], $id]);
    audit_log('housekeeping.start', 'task', $id);
    json_ok([], 'Task started');
}

if (($method === 'PUT' || $method === 'PATCH') && $action === 'complete') {
    require_permission('tickets.manage');
    if (!$id) json_error('id required', 422);
    $pdo = db();
    $pdo->beginTransaction();
    try {
        $pdo->prepare('UPDATE housekeeping_tasks SET status="completed", completed_at=NOW() WHERE id=?')->execute([$id]);
        $room = $pdo->prepare('SELECT room_id, task_type FROM housekeeping_tasks WHERE id=?');
        $room->execute([$id]);
        $info = $room->fetch();
        if ($info && in_array($info['task_type'], ['checkout_clean','daily_clean','deep_clean'], true)) {
            $pdo->prepare('UPDATE rooms SET housekeeping_status="clean", last_cleaned_at=NOW(), last_cleaned_by=? WHERE id=?')->execute([current_user()['id'], (int)$info['room_id']]);
        } elseif ($info && $info['task_type'] === 'inspection') {
            $pdo->prepare('UPDATE rooms SET housekeeping_status="inspected" WHERE id=?')->execute([(int)$info['room_id']]);
        }
        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack(); throw $e;
    }
    audit_log('housekeeping.complete', 'task', $id);
    json_ok([], 'Task completed');
}

if ($method === 'PUT' || $method === 'PATCH') {
    require_permission('tickets.manage');
    if (!$id) json_error('id required', 422);
    $allowed = ['task_type','priority','status','assigned_to','scheduled_date','notes'];
    $sets = []; $params = [];
    foreach ($allowed as $f) if (array_key_exists($f, $d)) { $sets[] = "$f = ?"; $params[] = $d[$f]; }
    if (!$sets) json_error('No fields to update', 422);
    $params[] = $id;
    db()->prepare('UPDATE housekeeping_tasks SET ' . implode(', ', $sets) . ' WHERE id = ?')->execute($params);
    audit_log('housekeeping.update', 'task', $id);
    json_ok([], 'Updated');
}

if ($method === 'DELETE') {
    require_permission('tickets.manage');
    if (!$id) json_error('id required', 422);
    db()->prepare('DELETE FROM housekeeping_tasks WHERE id = ?')->execute([$id]);
    audit_log('housekeeping.delete', 'task', $id);
    json_ok([], 'Deleted');
}

json_error('Method not allowed', 405);
