<?php
// api/users.php
require_once __DIR__ . '/db.php';
session_start();

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

function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendResponse(['error' => 'Unauthorized. Please login.'], 401);
}

$db = Database::getInstance()->getConnection();
$method = $_SERVER['REQUEST_METHOD'];

// GET /api/users.php?search=query
if ($method === 'GET') {
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
    if (empty($search)) {
        sendResponse(['users' => []]);
    }

    // Vyhledáváme uživatele podle username nebo emailu (včetně aktuálního uživatele)
    $stmt = $db->prepare('
        SELECT id, username, email 
        FROM users 
        WHERE username LIKE ? OR email LIKE ?
        LIMIT 10
    ');
    
    $searchTerm = '%' . $search . '%';
    $stmt->execute([$searchTerm, $searchTerm]);
    $users = $stmt->fetchAll();

    sendResponse(['users' => $users]);
}
elseif ($method === 'PUT') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $oldPassword = $input['old_password'] ?? '';
    $newPassword = $input['new_password'] ?? '';

    if (empty($oldPassword) || empty($newPassword)) {
        sendResponse(['error' => 'Old and new passwords are required.'], 400);
    }

    if (strlen($newPassword) < 6) {
        sendResponse(['error' => 'New password must be at least 6 characters long.'], 400);
    }

    $stmt = $db->prepare('SELECT password_hash FROM users WHERE id = ?');
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($oldPassword, $user['password_hash'])) {
        sendResponse(['error' => 'Incorrect old password.'], 401);
    }

    $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
    $stmtUpdate = $db->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
    $stmtUpdate->execute([$newHash, $_SESSION['user_id']]);

    sendResponse(['message' => 'Password updated successfully.']);
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
