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

// Database connection
require('dbcon.php');

// Decode incoming JSON
$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);

// Log raw input (for debugging)
file_put_contents("log.txt", $rawInput . PHP_EOL, FILE_APPEND);

// Validate required fields
$required = ['emailOrPhone', 'fromAccount', 'toAccount', 'recipientName', 'recipientBank', 'amount', 'note', 'transactionPin'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        echo json_encode(["status" => "error", "message" => "Missing field: $field"]);
        exit;
    }
}

// Extract data
$emailOrPhone   = trim($data['emailOrPhone']);
$fromAccount    = trim($data['fromAccount']);
$toAccount      = trim($data['toAccount']);
$recipientName  = trim($data['recipientName']);
$recipientBank  = trim($data['recipientBank']);
$amount         = floatval($data['amount']);
$note           = trim($data['note']);
$transactionPin = trim($data['transactionPin']);
$saveBeneficiary = isset($data['saveBeneficiary']) ? intval($data['saveBeneficiary']) : 0;

// Step 1: Verify user and account
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = '$emailOrPhone' ||  phone = '$emailOrPhone' ");
$stmt->execute([$emailOrPhone, $fromAccount]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(["status" => "error", "message" => "Invalid user or account number."]);
    exit;
}

// Step 2: Verify PIN (using MD5)
if (md5($transactionPin) !== $user['transaction_pin']) {
    echo json_encode(["status" => "error", "message" => "Incorrect transaction PIN."]);
    exit;
}

// Step 3: Check balance
$currentBalance = floatval($user['balance']);
if ($currentBalance < $amount) {
    $stmt = $pdo->prepare("INSERT INTO notifications 
        (emailOrPhone, fromAccount, toAccount, recipientName, recipientBank, amount, note, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$emailOrPhone, $fromAccount, $toAccount, $recipientName, $recipientBank, $amount, $note, "insufficient_funds"]);

    echo json_encode(["status" => "error", "message" => "Insufficient funds."]);
    exit;
}

// Step 4: Deduct amount
$newBalance = $currentBalance - $amount;
$update = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
$update->execute([$newBalance, $user['id']]);

// Step 5: Transaction reference
$transactionRef = "TXN" . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 10));

// Step 6: Record transaction
$stmt = $pdo->prepare("INSERT INTO transactions 
    (transaction_ref, emailOrPhone, fromAccount, toAccount, recipientName, recipientBank, amount, note, type, status, balance_before, balance_after, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
$stmt->execute([
    $transactionRef,
    $emailOrPhone,
    $fromAccount,
    $toAccount,
    $recipientName,
    $recipientBank,
    $amount,
    $note,
    "debit",
    "success",
    $currentBalance,
    $newBalance
]);

// Step 7: Record notification
$stmt = $pdo->prepare("INSERT INTO notifications 
    (emailOrPhone, transaction_ref, fromAccount, toAccount, recipientName, recipientBank, amount, note, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
$stmt->execute([
    $emailOrPhone,
    $transactionRef,
    $fromAccount,
    $toAccount,
    $recipientName,
    $recipientBank,
    $amount,
    $note,
    "success"
]);

// Step 8: Response
echo json_encode([
    "status" => "success",
    "message" => "Payment of ?" . number_format($amount, 2) . " to " . $recipientName . " successful.",
    "transaction_ref" => $transactionRef,
    "new_balance" => number_format($newBalance, 2)
]);
?>
