<?php
// ============================================================
// backend/api/auth/AuthController.php
// ============================================================

class AuthController {

    private PDO $db;

    public function __construct() {
        $this->db = getDB();
    }

    // POST /auth/register
    public function register(): void {
        $body = $GLOBALS['body'];
        $name  = trim($body['name']  ?? '');
        $email = trim($body['email'] ?? '');
        $pass  = trim($body['password'] ?? '');

        // Validate
        $errors = [];
        if (!$name)                        $errors['name']     = 'Name is required';
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors['email'] = 'Valid email required';
        if (strlen($pass) < 6)             $errors['password'] = 'Password must be at least 6 characters';

        if ($errors) sendError('Validation failed', 422, $errors);

        // Check duplicate
        $stmt = $this->db->prepare('SELECT id FROM users WHERE email = ?');
        $stmt->execute([$email]);
        if ($stmt->fetch()) sendError('Email already registered', 409);

        // Insert
        $hash = password_hash($pass, PASSWORD_BCRYPT, ['cost' => 12]);
        $stmt = $this->db->prepare(
            'INSERT INTO users (name, email, password) VALUES (?, ?, ?)'
        );
        $stmt->execute([$name, $email, $hash]);
        $id = (int) $this->db->lastInsertId();

        $token = generateJWT(['id' => $id, 'email' => $email, 'role' => 'user']);

        sendSuccess([
            'token' => $token,
            'user'  => ['id' => $id, 'name' => $name, 'email' => $email, 'role' => 'user'],
        ], 'Registration successful', 201);
    }

    // POST /auth/login
    public function login(): void {
        $body  = $GLOBALS['body'];
        $email = trim($body['email']    ?? '');
        $pass  = trim($body['password'] ?? '');

        if (!$email || !$pass) sendError('Email and password required', 422);

        $stmt = $this->db->prepare('SELECT * FROM users WHERE email = ?');
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($pass, $user['password'])) {
            sendError('Invalid email or password', 401);
        }

        $token = generateJWT([
            'id'    => $user['id'],
            'email' => $user['email'],
            'role'  => $user['role'],
        ]);

        sendSuccess([
            'token' => $token,
            'user'  => [
                'id'    => $user['id'],
                'name'  => $user['name'],
                'email' => $user['email'],
                'role'  => $user['role'],
            ],
        ], 'Login successful');
    }

    // GET /auth/me   (requires token)
    public function me(): void {
        $payload = requireAuth();
        $stmt    = $this->db->prepare('SELECT id, name, email, role, created_at FROM users WHERE id = ?');
        $stmt->execute([$payload['id']]);
        $user = $stmt->fetch();
        if (!$user) sendError('User not found', 404);
        sendSuccess($user);
    }
}
