<?php
/**
 * Login 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_password = isset($_POST['user_password']) ? $_POST['user_password'] : '';
    $remember_me = isset($_POST['remember_me']) ? true : false;
    
    // Validate email
    if (empty($user_email)) {
        $errors[] = $translation['tr_158'];
    } elseif (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = $translation['tr_163'];
    }
    
    // Validate password
    if (empty($user_password)) {
        $errors[] = $translation['tr_160'];
    }
    
    if (empty($errors)) {
        
        $encrypted_password = hash('sha512', $user_password);
        
        // Check if user exists
        $statement = $connect->prepare("SELECT * FROM users WHERE user_email = :user_email AND user_status = 1");
        $statement->execute(array(':user_email' => $user_email));
        $result = $statement->fetch();
        
        if ($result == false) {
            $errors[] = $translation['tr_172'];
        } else {
            // Verify password
            $statement = $connect->prepare("SELECT * FROM users WHERE user_email = :user_email AND user_password = :user_password AND user_status = 1");
            $statement->execute(array(
                ':user_email' => $user_email,
                ':user_password' => $encrypted_password
            ));
            
            $result_login = $statement->fetch();
            
            if ($result_login !== false) {
                
                // Generate 6-digit verification code
                $verification_code = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
                
                // Store verification code in database
                $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));
                $ip_address = getClientIp(1);
                
                $stmt = $connect->prepare("INSERT INTO verification_codes (user_email, verification_code, expires_at, ip_address) VALUES (:user_email, :verification_code, :expires_at, :ip_address)");
                $stmt->execute([
                    ':user_email' => $user_email,
                    ':verification_code' => $verification_code,
                    ':expires_at' => $expires_at,
                    ':ip_address' => $ip_address
                ]);
                
                // Send verification code via email
                $array_content = array(
                    "{LOGO_URL}" => $urlPath->image($theme['th_logo']),
                    "{SITE_DOMAIN}" => $urlPath->home(),
                    "{SITE_NAME}" => $translation['tr_1'],
                    "{USER_NAME}" => $result_login['user_name'],
                    "{VERIFICATION_CODE}" => $verification_code
                );
                
                $emailTemplate = getEmailTemplate($connect, 3); // 2FA template ID
                
                if ($emailTemplate) {
                    $emailContent = json_decode($emailTemplate['email_content'], true);
                    $emailSent = @sendMail(
                        $array_content,
                        $emailContent[0]['message'],
                        $user_email,
                        $emailTemplate['email_fromname'],
                        $emailContent[0]['subject'],
                        $emailTemplate['email_plaintext']
                    );
                }
                
                // Store user info in session temporarily for verification
                $_SESSION['pending_2fa'] = true;
                $_SESSION['pending_user_email'] = $user_email;
                $_SESSION['pending_user_name'] = $result_login['user_name'];
                $_SESSION['pending_user_id'] = $result_login['user_id'];
                $_SESSION['pending_remember_me'] = $remember_me;
                
                echo json_encode([
                    'success' => true,
                    'requires_2fa' => true,
                    'redirect' => SITE_URL . '/verify-otp.php'
                ]);
                exit;
                
            } else {
                $errors[] = $translation['tr_174'];
            }
        }
    }
}

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