<?php
// backend/controllers/AuthController.php
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../utils/Auth.php';

class AuthController {
    private $userModel;

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

    public function register() {
        $data = json_decode(file_get_contents("php://input"), true);
        
        if (!isset($data['email']) || !isset($data['password']) || !isset($data['full_name'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields']);
            return;
        }

        if ($this->userModel->findByEmail($data['email'])) {
            http_response_code(409);
            echo json_encode(['error' => 'Email already exists']);
            return;
        }

        $userId = $this->userModel->create($data['email'], $data['password'], $data['full_name']);
        if ($userId) {
            Auth::login($userId);
            echo json_encode(['success' => true, 'user_id' => $userId, 'full_name' => $data['full_name']]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Registration failed']);
        }
    }

    public function login() {
        $data = json_decode(file_get_contents("php://input"), true);
        
        if (!isset($data['email']) || !isset($data['password'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing email or password']);
            return;
        }

        $user = $this->userModel->findByEmail($data['email']);
        if ($user && password_verify($data['password'], $user['password_hash'])) {
            Auth::login($user['id']);
            echo json_encode(['success' => true, 'user_id' => $user['id'], 'full_name' => $user['full_name']]);
        } else {
            http_response_code(401);
            echo json_encode(['error' => 'Invalid credentials']);
        }
    }

    public function logout() {
        Auth::logout();
        echo json_encode(['success' => true]);
    }

    public function me() {
        Auth::requireLogin();
        $userModel = new User();
        $user = $userModel->findByEmail($_SESSION['user_email'] ?? '');
        echo json_encode(['user_id' => Auth::getUserId(), 'full_name' => $user['full_name'] ?? '']);
    }
}
?>