<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$input = hw_input_json();
$first = hw_sanitize_string($input['first_name'] ?? '');
$last = hw_sanitize_string($input['last_name'] ?? '');
$email = hw_sanitize_string($input['email'] ?? '');
$password = (string)($input['password'] ?? '');
$consent = (bool)($input['consent'] ?? false);

if (!$first || !$last) hw_json(['message' => 'First and last name are required'], 422);
if (!hw_validate_email($email)) hw_json(['message' => 'Valid email is required'], 422);
if (strlen($password) < 8) hw_json(['message' => 'Password must be at least 8 characters'], 422);
if (!$consent) hw_json(['message' => 'Consent is required'], 422);

try {
    $pdo = hw_db();
    // Check existing
    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    if ($stmt->fetch()) hw_json(['message' => 'Email already registered'], 409);

    $pdo->beginTransaction();

    // Create user
    $stmt = $pdo->prepare('INSERT INTO users (first_name, last_name, email, password_hash, status) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([$first, $last, $email, hw_hash_password($password), 'active']);
    $userId = (int)$pdo->lastInsertId();

    // Assign default role: client
    $stmt = $pdo->prepare('INSERT INTO user_roles (user_id, role_id) VALUES (?, 2)');
    $stmt->execute([$userId]);

    // Store consent
    $stmt = $pdo->prepare('INSERT INTO consent_forms (user_id, consent_type, accepted, accepted_at, ip_address, user_agent) VALUES (?, ?, 1, NOW(), ?, ?)');
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
    $stmt->execute([$userId, 'privacy_policy', $ipAddress, $userAgent]);

    // Audit log
    $stmt = $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("email", ?))');
    $stmt->execute([$userId, 'user_register', $email]);

    $pdo->commit();

    // Create session for auto-login
    session_start();
    $_SESSION['user_id'] = $userId;
    $_SESSION['email'] = $email;
    $_SESSION['first_name'] = $first;
    $_SESSION['last_name'] = $last;
    $_SESSION['role'] = 'client';

    hw_json(['message' => 'Account created successfully', 'user_id' => $userId]);
} catch (Throwable $e) {
    if ($pdo && $pdo->inTransaction()) { $pdo->rollBack(); }
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
