<?php
include_once __DIR__ . '/../config/database.php';
include_once __DIR__ . '/../models/User.php';

class AuthController {
    private $db;
    private $user;

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

    public function login($data) {
        if(!empty($data->username) && !empty($data->password)) {
            if($this->user->login($data->username, $data->password)) {
                // Создаем примитивный токен (в идеале использовать JWT)
                $token = base64_encode(json_encode([
                    "id" => $this->user->id,
                    "username" => $this->user->username,
                    "role" => $this->user->role,
                    "exp" => time() + 3600
                ]));

                http_response_code(200);
                echo json_encode([
                    "message" => "Успешный вход.",
                    "token" => $token,
                    "user" => [
                        "id"          => $this->user->id,
                        "username"    => $this->user->username,
                        "role"        => $this->user->role,
                        "full_name"   => $this->user->full_name,
                        "phone"       => $this->user->phone,
                        "postal_code" => $this->user->postal_code,
                        "email"       => $this->user->email
                    ]
                ]);
            } else {
                http_response_code(401);
                echo json_encode(["message" => "Неверный логин или пароль."]);
            }
        } else {
            http_response_code(400);
            echo json_encode(["message" => "Укажите логин и пароль."]);
        }
    }

    public function register($data) {
        if(!empty($data->username) && !empty($data->email) && !empty($data->password) && !empty($data->full_name)) {
            $this->user->username    = $data->username;
            $this->user->email       = $data->email;
            $this->user->password    = $data->password;
            $this->user->full_name   = $data->full_name;
            $this->user->phone       = $data->phone ?? '';
            $this->user->postal_code = $data->postal_code ?? '';

            if($this->user->create()) {
                http_response_code(201);
                echo json_encode(["message" => "Пользователь успешно создан."]);
            } else {
                http_response_code(503);
                echo json_encode(["message" => "Невозможно создать пользователя. Возможно такой username уже есть."]);
            }
        } else {
            http_response_code(400);
            echo json_encode(["message" => "Заполните все поля."]);
        }
    }
}
?>
