<?php
/**
 * API Register Endpoint - JSON response for mobile app
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// Only POST allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$password = $_POST['password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';

// Validate input
if (empty($name)) {
    echo json_encode(['success' => false, 'error' => 'Name is required']);
    exit;
}

if (empty($email)) {
    echo json_encode(['success' => false, 'error' => 'Email is required']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'error' => 'Invalid email format']);
    exit;
}

if (empty($password)) {
    echo json_encode(['success' => false, 'error' => 'Password is required']);
    exit;
}

if (strlen($password) < 6) {
    echo json_encode(['success' => false, 'error' => 'Password must be at least 6 characters']);
    exit;
}

if ($password !== $confirmPassword) {
    echo json_encode(['success' => false, 'error' => 'Passwords do not match']);
    exit;
}

try {
    // Check duplicate email
    $existing = dbFetch("SELECT id FROM users WHERE email = ?", [$email]);
    if ($existing) {
        echo json_encode(['success' => false, 'error' => 'Email already registered. Please login.']);
        exit;
    }

    // Split name into first/last
    $nameParts = explode(' ', $name, 2);
    $firstName = $nameParts[0];
    $lastName = $nameParts[1] ?? '';

    $hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
    $userId = 'U' . strtoupper(substr(md5(uniqid()), 0, 8));
    $referralCode = 'REF' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));

    $newUserId = dbInsert('users', [
        'user_id'       => $userId,
        'email'         => $email,
        'password'      => $hashedPassword,
        'first_name'    => $firstName,
        'last_name'     => $lastName,
        'name'          => $name,
        'phone'         => $phone,
        'status'        => 'active',
        'referral_code' => $referralCode,
        'created_at'    => date('Y-m-d H:i:s')
    ]);

    if (!$newUserId) {
        echo json_encode(['success' => false, 'error' => 'Registration failed. Please try again.']);
        exit;
    }

    // Create wallet
    $demoBalance = defined('DEMO_BALANCE') ? DEMO_BALANCE : 10000;
    dbInsert('user_wallets', [
        'user_id'      => $newUserId,
        'balance'      => 0,
        'demo_balance' => $demoBalance
    ]);

    // Auto-login: set session
    $_SESSION['user_id'] = $newUserId;
    $_SESSION['user_type'] = 'user';
    $_SESSION['user_email'] = $email;
    $_SESSION['account_type'] = 'demo';

    echo json_encode([
        'success' => true,
        'message' => 'Registration successful',
        'data' => [
            'id'            => (int)$newUserId,
            'user_id'       => $userId,
            'name'          => $name,
            'email'         => $email,
            'phone'         => $phone,
            'status'        => 'active',
            'kyc_status'    => 'pending',
            'referral_code' => $referralCode
        ]
    ]);

} catch (Exception $e) {
    error_log("API Register Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Server error. Please try again.']);
}
