<?php
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../helpers/Response.php';
require_once __DIR__ . '/../middlewares/AuthMiddleware.php';

class UserController
{
    private $db;
    private $user;

    public function __construct($db)
    {
        $this->db = $db;
        $this->user = new User($db);
    }

    public function profile()
    {
        // Protect this route
        $user = AuthMiddleware::authenticate();

        // Fetch user data
        $query = "SELECT id, name, email, phone, role, fcm_token, push_enabled, profile_photo FROM users WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(":id", $user->id);
        $stmt->execute();
        $userData = $stmt->fetch(PDO::FETCH_ASSOC);

        // Add full URL to profile photo if it exists
        if ($userData && $userData['profile_photo']) {
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
            $host = $_SERVER['HTTP_HOST'];
            // Remove /api/ from the URL path since uploads is in the root
            $userData['profile_photo_url'] = "$protocol://$host/" . $userData['profile_photo'];
        } else {
            $userData['profile_photo_url'] = null;
        }

        Response::success("Profile data.", $userData);
    }

    public function updateFcmToken()
    {
        $user = AuthMiddleware::authenticate();
        $data = json_decode(file_get_contents("php://input"), true);
        $token = $data['fcm_token'] ?? null;

        if (!$token) {
            Response::error("Token FCM é obrigatório.", 400);
        }

        if ($this->user->updateFcmToken($user->id, $token)) {
            Response::success("Token FCM atualizado.");
        } else {
            Response::error("Erro ao atualizar token FCM.", 500);
        }
    }

    public function updatePushSettings()
    {
        $user = AuthMiddleware::authenticate();
        $data = json_decode(file_get_contents("php://input"), true);
        $enabled = isset($data['push_enabled']) ? (int) $data['push_enabled'] : 1;

        if ($this->user->updatePushEnabled($user->id, $enabled)) {
            Response::success("Preferências de notificação atualizadas.");
        } else {
            Response::error("Erro ao atualizar preferências.", 500);
        }
    }

    public function updateRole()
    {
        $user = AuthMiddleware::authenticate();
        $data = json_decode(file_get_contents("php://input"), true);
        $role = $data['role'] ?? null;

        if (!$role) {
            Response::error("A função (role) é obrigatória.", 400);
        }

        if ($this->user->updateRole($user->id, $role)) {
            Response::success("Função de utilizador atualizada com sucesso.", ["role" => $role]);
        } else {
            Response::error("Erro ao atualizar função de utilizador.", 500);
        }
    }

    public function updateProfile()
    {
        $user = AuthMiddleware::authenticate();

        // Data can come from POST (multipart) or JSON
        $data = $_POST;
        if (empty($data)) {
            $json = json_decode(file_get_contents("php://input"), true);
            if ($json)
                $data = $json;
        }

        $updateData = [];
        if (isset($data['name']) && !empty(trim($data['name'])))
            $updateData['name'] = $data['name'];
        // Email is immutable — never update it from this endpoint
        if (isset($data['phone']) && !empty(trim($data['phone'])))
            $updateData['phone'] = $data['phone'];

        // Handle profile photo upload
        if (isset($_FILES['profile_photo'])) {
            $target_dir = "../uploads/profiles/";
            if (!file_exists($target_dir)) {
                mkdir($target_dir, 0777, true);
            }

            $file_extension = pathinfo($_FILES["profile_photo"]["name"], PATHINFO_EXTENSION);
            $new_filename = "user_" . $user->id . "_" . time() . "." . $file_extension;
            $target_file = $target_dir . $new_filename;

            if (move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $target_file)) {
                $updateData['profile_photo'] = "uploads/profiles/" . $new_filename;
            }
        }

        if (empty($updateData)) {
            Response::error("Nenhum dado para atualizar.", 400);
            return;
        }

        try {
            if ($this->user->updateProfile($user->id, $updateData)) {
                // Fetch updated data
                $query = "SELECT id, name, email, phone, role, profile_photo FROM users WHERE id = :id";
                $stmt = $this->db->prepare($query);
                $stmt->bindParam(":id", $user->id);
                $stmt->execute();
                $updatedUser = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($updatedUser['profile_photo']) {
                    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                    $host = $_SERVER['HTTP_HOST'];
                    // Remove /api/ from the URL path since uploads is in the root
                    $updatedUser['profile_photo_url'] = "$protocol://$host/" . $updatedUser['profile_photo'];
                }

                Response::success("Perfil atualizado com sucesso.", $updatedUser);
            } else {
                Response::error("Erro ao atualizar perfil.", 500);
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                Response::error("O telefone informado já está em uso por outra conta.", 409);
            } else {
                Response::error("Erro interno do servidor: " . $e->getMessage(), 500);
            }
        }
    }
}
?>