<?php
require_once __DIR__ . '/../../config/db.php';

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

// This webhook is called by your SMS Bot application
// Expected fields: sender (e.g., Arab Bank), message (SMS text), timestamp
$input = json_decode(file_get_contents('php://input'), true);
$message = $input['message'] ?? '';
$sender = $input['sender'] ?? '';

if (empty($message)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Empty message']);
    exit;
}

// 1. Log the incoming SMS for debugging
error_log("JordanBot SMS Received: Sender: [$sender], Content: [$message]");

// 2. Extract Reference Code (Pattern: JB-XXXXXX)
// Matches JB- followed by 6 alphanumeric characters
preg_match('/JB-([A-Z0-9]{6})/', strtoupper($message), $matches);
$refCode = isset($matches[0]) ? $matches[0] : null;

// 3. Extract Amount (Pattern: finds decimal numbers)
// Note: Jordan uses 'JOD' or 'دينار'
preg_match('/([0-9]+(\.[0-9]{2})?)/', $message, $amtMatches);
$amountReceived = isset($amtMatches[0]) ? floatval($amtMatches[0]) : 0;

if (!$refCode) {
    echo json_encode(['success' => false, 'message' => 'No Reference Code found in SMS']);
    exit;
}

try {
    // 4. Find the pending payment
    $stmt = $pdo->prepare("SELECT * FROM cliq_payments WHERE reference_code = :ref AND status = 'pending' LIMIT 1");
    $stmt->execute([':ref' => $refCode]);
    $payment = $stmt->fetch();

    if ($payment) {
        // Optional: Verify amount match (allowing for minor differences or currency symbols)
        if (abs($payment['amount'] - $amountReceived) > 0.05) {
            error_log("JordanBot: Amount mismatch for $refCode. Expected: {$payment['amount']}, Received: $amountReceived");
            // We can still proceed or mark for manual review
        }

        $pdo->beginTransaction();

        // 5. Update payment status
        $stmt = $pdo->prepare("UPDATE cliq_payments SET status = 'paid' WHERE id = :id");
        $stmt->execute([':id' => $payment['id']]);

        // 6. Activate/Extend Subscription
        $fingerprint = $payment['fingerprint'];
        $plan = $payment['plan'];
        
        // Calculate expiration (e.g. basic=30 days, annual=365 days)
        $days = ($plan === 'annual') ? 365 : 30;
        $expiresAt = date('Y-m-d H:i:s', strtotime("+$days days"));

        // Check if user already has a subscription to extend it
        $stmtCheck = $pdo->prepare("SELECT id, expires_at FROM subscriptions WHERE fingerprint = :fingerprint AND is_active = 1 LIMIT 1");
        $stmtCheck->execute([':fingerprint' => $fingerprint]);
        $existing = $stmtCheck->fetch();

        if ($existing) {
            // Extend existing
            $newExpiry = date('Y-m-d H:i:s', strtotime($existing['expires_at'] . " +$days days"));
            $stmtUpdate = $pdo->prepare("UPDATE subscriptions SET expires_at = :expiry, plan = :plan WHERE id = :id");
            $stmtUpdate->execute([':expiry' => $newExpiry, ':plan' => $plan, ':id' => $existing['id']]);
        } else {
            // Create new
            $stmtInsert = $pdo->prepare("INSERT INTO subscriptions (fingerprint, plan, expires_at, is_active) VALUES (:fingerprint, :plan, :expiry, 1)");
            $stmtInsert->execute([':fingerprint' => $fingerprint, ':plan' => $plan, ':expiry' => $expiresAt]);
        }

        $pdo->commit();
        
        error_log("JordanBot: Subscription activated for $fingerprint via $refCode ($plan)");
        echo json_encode(['success' => true, 'message' => "Subscription activated for $refCode"]);

    } else {
        echo json_encode(['success' => false, 'message' => 'Reference code not found or already processed']);
    }
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
