<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * API: Update Room Status
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set JSON header
header('Content-Type: application/json');

// Calculate base path
$base_path = null;
$base_path = dirname(__DIR__, 2); // Go up 2 levels from api/ to HMSPOS/

if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Initialize system
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/helpers.php';
require_once $base_path . '/config/auth.php';

// Load csrf if exists
if (file_exists($base_path . '/config/csrf.php')) {
    require_once $base_path . '/config/csrf.php';
}

// Define verify_csrf_token if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return true; // Bypass for now
    }
}

// Require authentication
require_auth();

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Method not allowed'
    ]);
    exit;
}

// Verify CSRF token
if (defined('CSRF_TOKEN_NAME') && !verify_csrf_token($_POST['csrf_token'] ?? '')) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid security token'
    ]);
    exit;
}

// Get parameters
$room_id = isset($_POST['room_id']) ? (int)$_POST['room_id'] : 0;
$field = isset($_POST['field']) ? $_POST['field'] : '';
$value = isset($_POST['value']) ? $_POST['value'] : '';

if (!$room_id) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Room ID is required'
    ]);
    exit;
}

if (!in_array($field, ['status', 'housekeeping_status'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid field'
    ]);
    exit;
}

try {
    // Begin transaction
    if (function_exists('begin_transaction')) {
        begin_transaction();
    }
    
    // Update room status
    $sql = "UPDATE rooms SET $field = ?, updated_at = NOW() WHERE room_id = ?";
    $result = db_execute($sql, [$value, $room_id]);
    
    if ($result === false) {
        throw new Exception('Failed to update room status');
    }
    
    // If marking as dirty, create a cleaning task
    if ($field === 'housekeeping_status' && $value === 'dirty') {
        // Check if there's already a pending task for this room
        $existing_task = db_fetch_value("
            SELECT COUNT(*) FROM hk_tasks 
            WHERE room_id = ? AND status IN ('pending', 'assigned', 'in_progress')
        ", [$room_id]);
        
        if (!$existing_task) {
            $task_code = 'HK-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
            
            db_insert('hk_tasks', [
                'task_code' => $task_code,
                'room_id' => $room_id,
                'task_type' => 'cleaning',
                'priority' => 'medium',
                'status' => 'pending',
                'notes' => 'Auto-created from status update',
                'created_by' => $current_user['user_id'] ?? 0,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }
    }
    
    // Log the action
    if (function_exists('log_activity')) {
        log_activity($current_user['user_id'] ?? 0, 'update', 'rooms', $room_id, "Updated $field to $value");
    }
    
    // Commit transaction
    if (function_exists('commit_transaction')) {
        commit_transaction();
    }
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Room status updated successfully',
        'data' => [
            'room_id' => $room_id,
            'field' => $field,
            'value' => $value
        ]
    ]);
    
} catch (Exception $e) {
    // Rollback on error
    if (function_exists('rollback_transaction')) {
        rollback_transaction();
    }
    
    error_log("Error updating room status: " . $e->getMessage());
    
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}