<?php
ob_start();
date_default_timezone_set('UTC');
header('Content-Type: application/json');

register_shutdown_function(function () {
    $error = error_get_last();
    if ($error !== null && !headers_sent()) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Fatal error: ' . $error['message']
        ]);
    }
});

function sendResponse($success, $message) {
    if (ob_get_length()) ob_end_clean();
    echo json_encode(['success' => $success, 'message' => $message]);
    exit;
}

// ============================================
// OTP DETECTOR CLASS (UNCHANGED)
// ============================================
class OTPDetector {
    public static function detectOTP($message, $minLength = 4, $maxLength = 10) {

        $wordSeqOtp = self::extractWordDigitSequence($message, $minLength, $maxLength);
        if ($wordSeqOtp) {
            return ['otp' => $wordSeqOtp, 'type' => 'numeric', 'confidence' => 'high'];
        }

        if (preg_match('/^([A-Z0-9]{' . $minLength . ',' . $maxLength . '})\s+is\s+/i', $message, $matches)) {
            return [
                'otp' => $matches[1],
                'type' => self::getOTPType($matches[1]),
                'confidence' => 'high'
            ];
        }

        $patterns = [
            '/(?:OTP|code|verification code|pin|password|token)(?:\s*is)?[\s:]+([A-Z0-9]{' . $minLength . ',' . $maxLength . '})\b/i',
            '/(?:your|the)\s+(?:OTP|code|verification code|pin|password|token)[\s:]+([A-Z0-9]{' . $minLength . ',' . $maxLength . '})\b/i',
            '/\b([A-Z0-9]{' . $minLength . ',' . $maxLength . '})\s+(?:is|as)\s+(?:your|the)\s*(?:OTP|code|verification code)/i'
        ];

        foreach ($patterns as $p) {
            if (preg_match($p, $message, $m)) {
                return ['otp' => $m[1], 'type' => self::getOTPType($m[1]), 'confidence' => 'high'];
            }
        }

        if (preg_match('/\b(\d{' . $minLength . ',' . $maxLength . '})\b/', $message, $m)) {
            return ['otp' => $m[1], 'type' => 'numeric', 'confidence' => 'medium'];
        }

        return null;
    }

    private static function getOTPType($otp) {
        $hasLetters = preg_match('/[A-Z]/i', $otp);
        $hasNumbers = preg_match('/[0-9]/', $otp);
        return ($hasLetters && $hasNumbers) ? 'alphanumeric' : ($hasNumbers ? 'numeric' : 'alphabetic');
    }

    private static function extractWordDigitSequence($message, $minLength, $maxLength) {
        $map = ['zero'=>'0','one'=>'1','two'=>'2','three'=>'3','four'=>'4','five'=>'5','six'=>'6','seven'=>'7','eight'=>'8','nine'=>'9'];

        if (!preg_match('/\b(?:zero|one|two|three|four|five|six|seven|eight|nine)(?:[\s-]+(?:zero|one|two|three|four|five|six|seven|eight|nine)){3,}\b/i', $message, $m)) {
            return null;
        }

        $parts = preg_split('/[\s-]+/', strtolower($m[0]));
        $digits = '';

        foreach ($parts as $w) {
            if (!isset($map[$w])) return null;
            $digits .= $map[$w];
        }

        return (strlen($digits) >= $minLength && strlen($digits) <= $maxLength) ? $digits : null;
    }
}

// ============================================
// MAIN
// ============================================

try {
    // === DB CONNECTION (MySQLi) ===
    $conn = mysqli_connect('localhost', 'u216559739_otp_logs', 'r4N6n3lYFPED', 'u216559739_otp_logs');

    if (!$conn) {
        sendResponse(false, "DB connection failed");
    }

    mysqli_set_charset($conn, "utf8mb4");

    // === USER AGENT CHECK ===
    $allowedUA = ['MyApp/6.1', 'MyApp/7.4'];
    if (!in_array($_SERVER['HTTP_USER_AGENT'] ?? '', $allowedUA, true)) {
        sendResponse(false, "Invalid user-agent.");
    }

    // === INPUT ===
    $message = trim($_POST['message'] ?? '');
    if (strlen($message) < 5) {
        sendResponse(false, "Invalid or empty message.");
    }

    $sender = trim($_POST['sender'] ?? '');
    $phone_number = '';

    if (preg_match('/Sender:\s*(\d{11})/i', $message, $m)) {
        $phone_number = $m[1];
    }
    $otp = '';

    // === SPECIAL HANDLING FOR NAGAD ===
    if (strtoupper($sender) === 'NAGAD') {
        if (preg_match('/\bOTP.*?\bis\s+(\d{4,10})\b/i', $message, $m)) {
            $otp = $m[1];
        }
    }
    
    // === FALLBACK TO DEFAULT DETECTOR ===
    if (!$otp) {
        $otpResult = OTPDetector::detectOTP($message);
        $otp = $otpResult['otp'] ?? '';
    }

    if (strpos($message, '0183723681') !== false) {
        $otp = '0183723681';
    }

    $simSlot = trim($_POST['simSlot'] ?? '');
    preg_match('/\d+/', $simSlot, $sim_matches);
    $sim_slot_number = $sim_matches[0] ?? '';
    $phone_key = 'phoneNumber' . $sim_slot_number;

    if (empty($phone_number)) {
        $phone_number = trim($_POST[$phone_key] ?? '');
    }

    $sim_slot  = 'SIM ' . $sim_slot_number;
    $timestamp = time();

    // === INSERT QUERY ===
    $stmt = mysqli_prepare($conn, "INSERT INTO sms_log (sender, otp, sim_slot, phone_number, timestamp, full_message) VALUES (?, ?, ?, ?, ?, ?)");

    if (!$stmt) {
        sendResponse(false, "Prepare failed");
    }

    mysqli_stmt_bind_param($stmt, "ssssis", $sender, $otp, $sim_slot, $phone_number, $timestamp, $message);

    if (!mysqli_stmt_execute($stmt)) {
        sendResponse(false, "Insert failed");
    }

    if (!$otp) {
        sendResponse(true, "OTP not found. Full message stored.");
    }

    if (!$phone_number) {
        sendResponse(false, "Missing phone number.");
    }

    sendResponse(true, "OTP saved successfully.");

} catch (Exception $e) {
    sendResponse(false, "Server Error: " . $e->getMessage());
}
?>