<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

include "includes/db_connect.php";
include "includes/auth.php";
checkAdmin();
// fraud_engine.php
require_once 'includes/db_connect.php';
require_once 'includes/functions.php'; // your send_sms function

$adminNumber = '0553747033'; // replace with your admin number

// ---------------------------
// Fetch unprocessed transactions
// ---------------------------
$sql = "SELECT t.*, 
               u.user_type, 
               (SELECT COUNT(*) FROM transactions t2 
                WHERE t2.sender_msisdn = t.sender_msisdn 
                AND t2.created_at >= DATE_SUB(t.created_at, INTERVAL 1 HOUR)) AS recent_txn_count
        FROM transactions t
        LEFT JOIN users u ON u.msisdn = t.sender_msisdn
        WHERE t.risk_score = 0"; // only unprocessed
$res = $conn->query($sql);

if ($res->num_rows == 0) {
    echo "No new transactions to process.\n";
    exit;
}

// ---------------------------
// Helper functions
// ---------------------------
function calculateRiskScore($txn) {
    $score = 0;

    // High amount (>1000 GHS)
    if ($txn['send_amount'] > 1000) $score += 40;

    // New recipient (recipient has no previous transactions)
    if ($txn['recent_txn_count'] == 1) $score += 20;

    // Cross-country transaction
    if ($txn['from_country'] != $txn['to_country']) $score += 25;

    // Multiple transactions in short time
    if ($txn['recent_txn_count'] > 5) $score += 30;

    return $score;
}

function determineRiskLevel($score) {
    if ($score >= 70) return 'HIGH';
    if ($score >= 40) return 'MEDIUM';
    return 'LOW';
}

function sendFraudAlertSMS($adminNumber, $txn) {
    $message = "🚨 HIGH RISK ALERT\n".
               "Txn ID: ".$txn['id']."\n".
               "Amount: ".$txn['send_amount']." GHS\n".
               "From: ".$txn['sender_msisdn']."\n".
               "To: ".$txn['receiver_msisdn']."\n".
               "Country: ".$txn['to_country'];
    send_sms($adminNumber, $message);
}

// ---------------------------
// Process transactions
// ---------------------------
while ($txn = $res->fetch_assoc()) {

    $score = calculateRiskScore($txn);
    $level = determineRiskLevel($score);
    $is_flagged = ($level == 'HIGH') ? 1 : 0;

    // Update transaction
    $stmt = $conn->prepare("
        UPDATE transactions
        SET risk_score=?, risk_level=?, is_flagged=?
        WHERE id=?
    ");
    $stmt->bind_param("isii", $score, $level, $is_flagged, $txn['id']);
    $stmt->execute();

    // Send alert SMS to admin if HIGH
    if ($is_flagged) {
        sendFraudAlertSMS($adminNumber, $txn);
    }

    echo "Processed Txn ID {$txn['id']} - Risk: $level - Score: $score\n";
}

echo "Fraud engine run complete.\n";