<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

// Include database config
$pdo = require_once __DIR__ . '/../../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = str_replace('/api/auth/', '', $path);

function response($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

// Routes
if ($path === 'register' && $method === 'POST') {
    $data = getJsonInput();
    
    if (empty($data['name']) || empty($data['email']) || empty($data['password'])) {
        response(['error' => 'Missing required fields'], 400);
    }
    
    $name = $data['name'];
    $email = $data['email'];
    $password = $data['password'];
    
    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        response(['error' => 'Invalid email format'], 400);
    }
    
    // Check if user exists
    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        response(['error' => 'Email already registered'], 409);
    }
    
    // Create user
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare('INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)');
    $stmt->execute([$name, $email, $hashedPassword]);
    $userId = $pdo->lastInsertId();
    
    // Create goals record
    $stmt = $pdo->prepare('INSERT INTO goals (user_id) VALUES (?)');
    $stmt->execute([$userId]);
    
    // Create settings record
    $stmt = $pdo->prepare('INSERT INTO settings (user_id) VALUES (?)');
    $stmt->execute([$userId]);
    
    // Generate session token
    $token = bin2hex(random_bytes(32));
    $_SESSION['user_id'] = $userId;
    $_SESSION['token'] = $token;
    
    response([
        'success' => true,
        'user_id' => $userId,
        'token' => $token,
        'message' => 'Registration successful'
    ], 201);
}

elseif ($path === 'login' && $method === 'POST') {
    $data = getJsonInput();
    
    if (empty($data['email']) || empty($data['password'])) {
        response(['error' => 'Missing email or password'], 400);
    }
    
    $stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
    $stmt->execute([$data['email']]);
    $user = $stmt->fetch();
    
    if (!$user || !password_verify($data['password'], $user['password_hash'])) {
        response(['error' => 'Invalid credentials'], 401);
    }
    
    $token = bin2hex(random_bytes(32));
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['token'] = $token;
    
    response([
        'success' => true,
        'user_id' => $user['id'],
        'token' => $token,
        'message' => 'Login successful'
    ]);
}

elseif ($path === 'logout' && $method === 'POST') {
    session_destroy();
    response(['success' => true, 'message' => 'Logout successful']);
}

elseif ($path === 'user' && $method === 'GET') {
    if (empty($_SESSION['user_id'])) {
        response(['error' => 'Unauthorized'], 401);
    }
    
    $stmt = $pdo->prepare('SELECT id, name, email, timezone, start_hour, ai_enabled, created_at FROM users WHERE id = ?');
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    
    response(['user' => $user]);
}

else {
    response(['error' => 'Not found'], 404);
}
?>
