<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

require('dbcon.php'); // Your PDO database connection
require __DIR__ . '/vendor/autoload.php'; // Firebase SDK

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

// === Initialize Firebase Messaging ===
$factory = (new Factory)->withServiceAccount(__DIR__.'/amstapay-firebase.json');
$messaging = $factory->createMessaging();

// === Read webhook POST body ===
$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);

// === Log webhook for debugging ===
file_put_contents("safehaven_webhook_log.txt", date('Y-m-d H:i:s') . " - " . $rawInput . PHP_EOL, FILE_APPEND);

// === Validate required fields ===
if (!isset($data['transaction_id']) || !isset($data['status'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Missing transaction_id or status"]);
    exit;
}

$transactionRef = $data['transaction_id'];
$status = $data['status'];
$amount = floatval($data['amount'] ?? 0);
$recipientEmailOrPhone = $data['recipient'] ?? null; // depends on payload
$note = $data['note'] ?? 'Payment via Safe Haven';

// === Optional: Verify webhook signature here ===
// Example: compare hash/signature from headers to prevent spoofing

// === Fetch transaction from DB ===
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE transaction_ref=?");
$stmt->execute([$transactionRef]);
$transaction = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$transaction) {
    // If transaction not found, you may create one
    $stmtInsert = $pdo->prepare("INSERT INTO transactions
        (transaction_ref, emailOrPhone, toAccount, amount, note, type, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmtInsert->execute([
        $transactionRef,
        $recipientEmailOrPhone,
        $data['toAccount'] ?? null,
        $amount,
        $note,
        "credit",
        $status
    ]);
} else {
    // Update transaction status
    $stmtUpdate = $pdo->prepare("UPDATE transactions SET status=?, updated_at=NOW() WHERE transaction_ref=?");
    $stmtUpdate->execute([$status, $transactionRef]);
}

// === Credit wallet if successful ===
if ($status === 'success') {
    $stmtUser = $pdo->prepare("SELECT id, balance FROM users WHERE email=? OR phone=?");
    $stmtUser->execute([$recipientEmailOrPhone, $recipientEmailOrPhone]);
    $user = $stmtUser->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $newBalance = $user['balance'] + $amount;
        $stmtBalance = $pdo->prepare("UPDATE users SET balance=? WHERE id=?");
        $stmtBalance->execute([$newBalance, $user['id']]);
    }
}

// === Send Firebase Notification ===
function sendFirebaseNotification($messaging, $tokens, $title, $body) {
    foreach ($tokens as $token) {
        $notification = Notification::create($title, $body);
        $message = CloudMessage::withTarget('token', $token)
            ->withNotification($notification);
        try {
            $messaging->send($message);
        } catch (Exception $e) {
            file_put_contents("fcm_errors.txt", $e->getMessage() . PHP_EOL, FILE_APPEND);
        }
    }
}

// Notify user
if ($user) {
    $stmtTokens = $pdo->prepare("SELECT fcm_token FROM user_devices WHERE user_id=? AND removed=0");
    $stmtTokens->execute([$user['id']]);
    $tokens = $stmtTokens->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($tokens)) {
        sendFirebaseNotification(
            $messaging,
            $tokens,
            $status === 'success' ? "Credit Alert" : "Payment Failed",
            "?" . number_format($amount, 2) . " " . ($status === 'success' ? "credited" : "failed") . " to your wallet."
        );
    }
}

// === Respond 200 OK to Safe Haven ===
http_response_code(200);
echo json_encode(["status" => "success", "message" => "Webhook processed"]);
?>
