<?php
// DMAppsESP Users API
require_once '../config/database.php';
require_once '../config/functions.php';

// CORS headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// Handle OPTIONS request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Authenticate user
$user_id = authenticate();

// Get request method and resource
$method = $_SERVER['REQUEST_METHOD'];
$request_uri = $_SERVER['REQUEST_URI'];
$path = parse_url($request_uri, PHP_URL_PATH);
$path_parts = explode('/', trim($path, '/'));
$resource_id = end($path_parts);

// Get action from query parameter
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'update':
        if ($method == 'POST') {
            update_user();
        }
        break;
        
    case 'reset_password':
        if ($method == 'POST') {
            reset_password();
        }
        break;
        
    case 'toggle_status':
        if ($method == 'POST') {
            toggle_status();
        }
        break;
        
    case 'activity':
        if ($method == 'GET') {
            get_user_activity();
        }
        break;
        
    case 'devices':
        if ($method == 'GET') {
            get_user_devices();
        }
        break;
        
    default:
        if ($method == 'GET') {
            if ($resource_id && is_numeric($resource_id)) {
                get_user($resource_id);
            } else {
                get_all_users();
            }
        } elseif ($method == 'POST') {
            create_user();
        } elseif ($method == 'PUT') {
            update_user();
        } elseif ($method == 'DELETE') {
            delete_user($resource_id);
        } else {
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
        }
        break;
}

function get_user($user_id) {
    global $con, $user_id;
    
    // Check if user is admin or requesting own data
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin' && $current_user['id'] != $user_id) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $stmt = $con->prepare("SELECT id, username, email, first_name, last_name, phone, role, status, created_at, last_login FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        echo json_encode($user);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
    }
}

function get_all_users() {
    global $con, $user_id;
    
    // Admin only
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $stmt = $con->prepare("
        SELECT u.id, u.username, u.email, u.first_name, u.last_name, u.phone, u.role, u.status, u.created_at, u.last_login,
               COUNT(d.id) as device_count
        FROM users u
        LEFT JOIN devices d ON u.id = d.owner_id
        GROUP BY u.id
        ORDER BY u.created_at DESC
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $users = [];
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
    
    echo json_encode($users);
}

function create_user() {
    global $con, $user_id;
    
    // Admin only
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['username']) || !isset($data['email']) || !isset($data['password'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        return;
    }
    
    // Check if user exists
    $stmt = $con->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $data['username'], $data['email']);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        http_response_code(409);
        echo json_encode(['error' => 'Username or email already exists']);
        return;
    }
    
    // Hash password
    $password_hash = password_hash($data['password'], PASSWORD_DEFAULT);
    
    $stmt = $con->prepare("
        INSERT INTO users (username, email, password_hash, first_name, last_name, phone, role) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("sssssss", 
        $data['username'], 
        $data['email'], 
        $password_hash,
        $data['first_name'] ?? null,
        $data['last_name'] ?? null,
        $data['phone'] ?? null,
        $data['role'] ?? 'user'
    );
    
    if ($stmt->execute()) {
        http_response_code(201);
        echo json_encode(['success' => true, 'user_id' => $con->insert_id]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create user']);
    }
}

function update_user() {
    global $con, $user_id;
    
    $data = json_decode(file_get_contents("php://input"), true);
    $target_user_id = $data['user_id'] ?? $user_id;
    
    // Check permissions
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin' && $current_user['id'] != $target_user_id) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $updates = [];
    $types = "";
    $params = [];
    
    if (isset($data['username'])) {
        $updates[] = "username = ?";
        $types .= "s";
        $params[] = $data['username'];
    }
    
    if (isset($data['email'])) {
        $updates[] = "email = ?";
        $types .= "s";
        $params[] = $data['email'];
    }
    
    if (isset($data['first_name'])) {
        $updates[] = "first_name = ?";
        $types .= "s";
        $params[] = $data['first_name'];
    }
    
    if (isset($data['last_name'])) {
        $updates[] = "last_name = ?";
        $types .= "s";
        $params[] = $data['last_name'];
    }
    
    if (isset($data['phone'])) {
        $updates[] = "phone = ?";
        $types .= "s";
        $params[] = $data['phone'];
    }
    
    if (isset($data['role']) && $current_user['role'] === 'admin') {
        $updates[] = "role = ?";
        $types .= "s";
        $params[] = $data['role'];
    }
    
    if (isset($data['status']) && $current_user['role'] === 'admin') {
        $updates[] = "status = ?";
        $types .= "s";
        $params[] = $data['status'];
    }
    
    if (empty($updates)) {
        http_response_code(400);
        echo json_encode(['error' => 'No fields to update']);
        return;
    }
    
    $updates[] = "updated_at = CURRENT_TIMESTAMP";
    $types .= "i";
    $params[] = $target_user_id;
    
    $sql = "UPDATE users SET " . implode(", ", $updates) . " WHERE id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param($types, ...$params);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update user']);
    }
}

function reset_password() {
    global $con, $user_id;
    
    // Admin only
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    $target_user_id = $data['user_id'] ?? null;
    
    if (!$target_user_id) {
        http_response_code(400);
        echo json_encode(['error' => 'User ID required']);
        return;
    }
    
    $new_password = 'password123'; // Default password
    $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
    
    $stmt = $con->prepare("UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
    $stmt->bind_param("si", $password_hash, $target_user_id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'new_password' => $new_password]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to reset password']);
    }
}

function toggle_status() {
    global $con, $user_id;
    
    // Admin only
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    $target_user_id = $data['user_id'] ?? null;
    
    if (!$target_user_id) {
        http_response_code(400);
        echo json_encode(['error' => 'User ID required']);
        return;
    }
    
    // Get current status
    $stmt = $con->prepare("SELECT status FROM users WHERE id = ?");
    $stmt->bind_param("i", $target_user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        return;
    }
    
    $user = $result->fetch_assoc();
    $new_status = $user['status'] === 'active' ? 'inactive' : 'active';
    
    $stmt = $con->prepare("UPDATE users SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
    $stmt->bind_param("si", $new_status, $target_user_id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'new_status' => $new_status]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update status']);
    }
}

function get_user_activity() {
    global $con, $user_id;
    
    $target_user_id = $_GET['user_id'] ?? $user_id;
    
    // Check permissions
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin' && $current_user['id'] != $target_user_id) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $stmt = $con->prepare("
        SELECT log_level, category, message, created_at 
        FROM system_logs 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 50
    ");
    $stmt->bind_param("i", $target_user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $activities = [];
    while ($row = $result->fetch_assoc()) {
        $activities[] = $row;
    }
    
    echo json_encode($activities);
}

function get_user_devices() {
    global $con, $user_id;
    
    $target_user_id = $_GET['user_id'] ?? $user_id;
    
    // Check permissions
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin' && $current_user['id'] != $target_user_id) {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    $stmt = $con->prepare("
        SELECT id, device_id, name, esp_model, status, last_seen 
        FROM devices 
        WHERE owner_id = ? 
        ORDER BY created_at DESC
    ");
    $stmt->bind_param("i", $target_user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $devices = [];
    while ($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }
    
    echo json_encode($devices);
}

function delete_user($user_id) {
    global $con;
    
    // Admin only
    $current_user = $_SESSION['user'];
    if ($current_user['role'] !== 'admin') {
        http_response_code(403);
        echo json_encode(['error' => 'Access denied']);
        return;
    }
    
    // Don't allow self-deletion
    if ($current_user['id'] == $user_id) {
        http_response_code(400);
        echo json_encode(['error' => 'Cannot delete your own account']);
        return;
    }
    
    $stmt = $con->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to delete user']);
    }
}
?>
