<?php
/**
 * Signup Controller
 */

// Suppress errors for clean JSON output
@ini_set('display_errors', '0');
@error_reporting(0);

// Start output buffering
ob_start();

// Mark as API endpoint
define('IS_API_ENDPOINT', true);

try {
    require '../core.php';
} catch (Exception $e) {
    ob_end_clean();
    header('Content-Type: application/json');
    http_response_code(200);
    echo json_encode(['success' => false, 'errors' => ['System error. Please try again.']]);
    exit;
}

// Clear buffer
ob_end_clean();

// Set JSON header
header('Content-Type: application/json');
http_response_code(200);

$errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $user_email = isset($_POST['user_email']) ? strtolower(trim($_POST['user_email'])) : '';
    $user_name = isset($_POST['user_name']) ? trim($_POST['user_name']) : '';
    $user_password = isset($_POST['user_password']) ? $_POST['user_password'] : '';
    $isChecked = isset($_POST['ischecked']) ? $_POST['ischecked'] : '';
    
    // Validate email
    if (empty($user_email)) {
        $errors[] = $translation['tr_158'];
    } elseif (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = $translation['tr_163'];
    }
    
    // Validate name
    if (empty($user_name)) {
        $errors[] = $translation['tr_159'];
    } elseif (strlen($user_name) < 3 || strlen($user_name) > 20) {
        $errors[] = $translation['tr_162'];
    } elseif (preg_match('/[^a-zA-Z0-9\s]/', $user_name)) {
        $errors[] = $translation['tr_171'];
    }
    
    // Validate password
    if (empty($user_password)) {
        $errors[] = $translation['tr_160'];
    } elseif (strlen($user_password) < 8 || strlen($user_password) > 32) {
        $errors[] = $translation['tr_164'];
    }
    
    // Validate terms checkbox
    if (empty($isChecked) || $isChecked != 1) {
        $errors[] = $translation['tr_173'];
    }
    
    if (empty($errors)) {
        
        // Check if email already exists
        $statement = $connect->prepare("SELECT * FROM users WHERE user_email = :user_email LIMIT 1");
        $statement->execute(array(':user_email' => $user_email));
        $result = $statement->fetch();
        
        if ($result != false) {
            $errors[] = $translation['tr_165'];
        }
    }
    
    if (empty($errors)) {
        
        $encrypted_password = hash('sha512', $user_password);
        
        // Insert new user
        $statement = $connect->prepare("
            INSERT INTO users (
                user_id, 
                user_name, 
                user_email, 
                user_password,
                user_status
            ) VALUES (
                null, 
                :user_name, 
                :user_email, 
                :user_password,
                1
            )
        ");
        
        $statement->execute(array(
            ':user_name' => $user_name,
            ':user_email' => $user_email,
            ':user_password' => $encrypted_password
        ));
        
        $user_id = $connect->lastInsertId();
        
        // Send welcome email (optional)
        $userInfo = array(
            'user_id' => $user_id,
            'user_name' => $user_name,
            'user_email' => $user_email
        );
        
        $array_content = array(
            "{LOGO_URL}" => $urlPath->image($theme['th_logo']),
            "{SITE_DOMAIN}" => $urlPath->home(),
            "{SITE_NAME}" => $translation['tr_1'],
            "{USER_NAME}" => $userInfo['user_name'],
            "{USER_EMAIL}" => $userInfo['user_email'],
            "{TERMS_URL}" => $urlPath->terms(),
            "{PRIVACY_URL}" => $urlPath->privacy(),
            "{SIGNIN_URL}" => $urlPath->signin()
        );
        
        $emailTemplate = getEmailTemplate($connect, 1);
        
        if ($emailTemplate) {
            $emailContent = json_decode($emailTemplate['email_content'], true);
            @sendMail(
                $array_content,
                $emailContent[0]['message'],
                $user_email,
                $emailTemplate['email_fromname'],
                $emailContent[0]['subject'],
                $emailTemplate['email_plaintext']
            );
        }
        
        // Log the user in automatically
        $_SESSION['signedin'] = true;
        $_SESSION['user_id'] = $userInfo['user_id'];
        $_SESSION['user_name'] = $userInfo['user_name'];
        $_SESSION['user_email'] = $userInfo['user_email'];
        
        echo json_encode([
            'success' => true,
            'redirect' => SITE_URL
        ]);
        exit;
    }
}

// Return errors
echo json_encode([
    'success' => false,
    'errors' => $errors
]);
exit;
