<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json');

// Use dynamic directory to avoid path issues on CyberPanel
require_once(__DIR__ . '/../../database/config.php');

// Log directory
$log_file = __DIR__ . '/webhook_incoming.log';

// Log everything for debugging
$raw_input = file_get_contents('php://input');
$headers = getallheaders();
file_put_contents($log_file, date('Y-m-d H:i:s') . " - Headers: " . json_encode($headers) . "\n", FILE_APPEND);
file_put_contents($log_file, date('Y-m-d H:i:s') . " - Processing Incoming Request\n", FILE_APPEND);

// If data is sent as JSON
if (empty($_POST) && !empty($raw_input)) {
    $json_data = json_decode($raw_input, true);
    if ($json_data) {
        $_POST = $json_data;
    }
}

// Security Check: Use a secret key
$valid_secret = "ri"; 
$provided_secret = $_SERVER['HTTP_X_SECRET_KEY'] ?? $_POST['secret_key'] ?? $_POST['secret'] ?? $headers['x-secret-key'] ?? $headers['X-Secret-Key'] ?? '';

if ($provided_secret !== $valid_secret) {
    file_put_contents($log_file, date('Y-m-d H:i:s') . " - Error: Unauthorized (Secret mismatch: $provided_secret)\n", FILE_APPEND);
    echo json_encode(['status_code' => 403, 'status' => 'Error', 'message' => 'Unauthorized']);
    exit;
}

// Get SMS Content
$message = $_POST['message'] ?? $_POST['text'] ?? '';
$sender = $_POST['sender'] ?? '';

if (empty($message)) {
    file_put_contents($log_file, date('Y-m-d H:i:s') . " - Error: Message empty\n", FILE_APPEND);
    echo json_encode(['status_code' => 400, 'status' => 'Error', 'message' => 'Message empty']);
    exit;
}

$amount = 0;
$utr = '';

// 1. Parse Amount
if (preg_match('/(?:Rs\.?|INR)\s*([\d,]+\.?\d*)/i', $message, $matches)) {
    $amount = str_replace(',', '', $matches[1]);
}

// 2. Parse UTR
if (preg_match('/(?:UPI Ref[:\s]+|Ref No[:\s]+|Ref[:\s]+)?\b(\d{12})\b/i', $message, $matches)) {
    $utr = $matches[1];
}

file_put_contents($log_file, date('Y-m-d H:i:s') . " - Parsed: Amount=$amount, UTR=$utr\n", FILE_APPEND);

if ($amount > 0 && !empty($utr)) {
    // Search for PENDING order
    $stmt = $conn->prepare("SELECT orderid, amount, txn_status FROM create_orders WHERE amount = ? AND txn_status = 'PENDING' AND (utr_number IS NULL OR utr_number = '' OR utr_number = ?) ORDER BY id DESC LIMIT 1");
    $stmt->execute([$amount, $utr]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($order) {
        $found_order_id = $order['orderid'];
        file_put_contents($log_file, date('Y-m-d H:i:s') . " - Match Found: $found_order_id\n", FILE_APPEND);
        
        // Update Order
        try {
            $txn_id = strtoupper(substr(md5($found_order_id . time()), 0, 12));
            $update = $conn->prepare("UPDATE create_orders SET txn_status = 'SUCCESS', utr_number = ?, transactions_id = COALESCE(NULLIF(transactions_id, ''), ?), received_from = 'SMS Auto' WHERE orderid = ?");
            
            if ($update->execute([$utr, $txn_id, $found_order_id])) {
                 file_put_contents($log_file, date('Y-m-d H:i:s') . " - DB Update Success\n", FILE_APPEND);
                 
                 // Callbacks and Managers with dynamic paths
                 $callbackFile = __DIR__ . '/../../partner/send_callback.php';
                 if (file_exists($callbackFile)) {
                     require_once($callbackFile);
                     if (function_exists('sendCallback')) {
                         sendCallback($conn, $found_order_id, 'SUCCESS');
                     }
                 }
                 
                 $poolFile = __DIR__ . '/../../database/UpiPoolManager.php';
                 if (file_exists($poolFile)) {
                     require_once($poolFile);
                     if (class_exists('UpiPoolManager')) {
                         $upiManager = new UpiPoolManager($conn);
                         $upiManager->updateTransactionStatus($found_order_id, 'success');
                     }
                 }

                 echo json_encode(['status_code' => 200, 'status' => 'Success', 'message' => 'Processed: ' . $found_order_id]);
            } else {
                 file_put_contents($log_file, date('Y-m-d H:i:s') . " - Update Failed: " . json_encode($update->errorInfo()) . "\n", FILE_APPEND);
            }
        } catch (Exception $e) {
            file_put_contents($log_file, date('Y-m-d H:i:s') . " - Critical Error: " . $e->getMessage() . "\n", FILE_APPEND);
        }
    } else {
        file_put_contents($log_file, date('Y-m-d H:i:s') . " - No Pending Order for Amount $amount\n", FILE_APPEND);
        echo json_encode(['status_code' => 404, 'status' => 'Not Found']);
    }
} else {
    echo json_encode(['status_code' => 400, 'status' => 'Invalid SMS']);
}
?>
