<?php
// user.php

include 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();

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

// Protect all routes with authentication
requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (!isset($_GET['idUser'])) {
        requirePermission('user_profile', 'view');
        http_response_code(400);
        echo json_encode(['error' => true, 'message' => 'User ID is required']);
        exit();
    }

    try {
        $query = "SELECT idUser, username, role, profile, active FROM users WHERE idUser = :idUser";
        $params = array(':idUser' => $_GET['idUser']);
        $result = metodGet($query, $params);
        $user = $result->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            http_response_code(404);
            echo json_encode(['error' => true, 'message' => 'User not found']);
            exit();
        }

        header('Content-Type: application/json');
        echo json_encode($user);
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => true, 'message' => 'Failed to fetch user data: ' . $e->getMessage()]);
        exit();
    }
}

if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);

    // Handle password update
    if (isset($_POST['password'])) {
        $idUser = $_GET['idUser'];
        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $user_upd = $_POST['user_upd'];

        $query = "UPDATE users SET password=:password, user_upd=:user_upd WHERE idUser=:idUser";
        $params = array(
            ':idUser' => $idUser,
            ':password' => $password,
            ':user_upd' => $user_upd
        );
        $result = metodPut($query, $params, 'users');
        echo json_encode(['success' => true, 'message' => 'Password updated successfully']);
        header("HTTP/1.1 200 OK");
        exit();
    }

    // Handle username update
    if (isset($_POST['username'])) {
        $idUser = $_GET['idUser'];
        $username = $_POST['username'];
        $user_upd = $_POST['user_upd'];

        // First check if username exists
        $checkQuery = "SELECT COUNT(*) as count FROM users WHERE username = :username AND idUser != :idUser";
        $checkParams = array(':username' => $username, ':idUser' => $idUser);
        $checkResult = metodGet($checkQuery, $checkParams);
        $count = $checkResult->fetch(PDO::FETCH_ASSOC)['count'];

        if ($count > 0) {
            http_response_code(400);
            echo json_encode(['error' => true, 'message' => 'Username already exists']);
            exit();
        }

        $query = "UPDATE users SET username=:username, user_upd=:user_upd WHERE idUser=:idUser";
        $params = array(
            ':idUser' => $idUser,
            ':username' => $username,
            ':user_upd' => $user_upd
        );
        
        try {
            $result = metodPut($query, $params, 'users');
            echo json_encode(['success' => true, 'message' => 'Username updated successfully']);
            header("HTTP/1.1 200 OK");
            exit();
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => true, 'message' => 'Failed to update username: ' . $e->getMessage()]);
            exit();
        }
    }

    // Handle regular user update
    requireAuth(['admin']) || requirePermission('user_profile', 'update');
    $idUser = $_GET['idUser'];
    $profile = $_POST['profile'];
    $role = $_POST['role'];
    $active = $_POST['active'];
    $user_upd = $_POST['user_upd'];
    $query = "UPDATE users SET user_upd=:user_upd, profile=:profile, 
              role=:role, active=:active 
              WHERE idUser=:idUser";
    $params = array(
        ':idUser' => $idUser,
        ':user_upd' => $user_upd,
        ':profile' => $profile,
        ':role' => $role,
        ':active' => $active
    );
    $result = metodPut($query, $params, 'users');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");