<?php
error_reporting(0);
ob_clean();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight OPTIONS request for CORS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require("dbcon.php");

try {
    // Get JSON input
    $input = json_decode(file_get_contents("php://input"), true);

    // Handle invalid or empty input
    if (!is_array($input)) {
        echo json_encode([
            'success' => false,
            'error' => 'Invalid JSON input.'
        ]);
        exit;
    }

    // For older PHP versions, use isset instead of ??
    $emailOrPhone = isset($input['emailOrPhone']) ? trim($input['emailOrPhone']) : null;

    if (!$emailOrPhone) {
        echo json_encode([
            'success' => false,
            'error' => 'Missing emailOrPhone parameter.'
        ]);
        exit;
    }

    // Prepare and execute query
    $stmt = $pdo->prepare("
        SELECT 
            transaction_ref,
            emailOrPhone,
            fromAccount,
            toAccount,
            recipientName,
            recipientBank,
            amount,
            note,
            type,
            status,
            balance_before,
            balance_after,
            created_at
        FROM transactions
        WHERE emailOrPhone = :emailOrPhone
        ORDER BY created_at DESC
    ");
    $stmt->bindParam(":emailOrPhone", $emailOrPhone);
    $stmt->execute();

    // If no results found
    if ($stmt->rowCount() === 0) {
        echo json_encode([
            'success' => false,
            'error' => 'No transactions found for ' . $emailOrPhone
        ]);
        exit;
    }

    // Build response
    $transactions = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $transactions[] = [
            'transaction_ref' => $row['transaction_ref'],
            'emailOrPhone' => $row['emailOrPhone'],
            'title' => ($row['status'] === 'success') ? 'Transaction Successful' : 'Transaction Update',
            'message' => "N" . number_format($row['amount']) . " sent to " . $row['recipientName'] . " (" . $row['recipientBank'] . ")",
            'type' => $row['type'],
            'timestamp' => $row['created_at'],
            'status' => $row['status'],
            'balance_before' => "N" . number_format($row['balance_before']),
            'balance_after' => "N" . number_format($row['balance_after']),
            'read' => false,
            'priority' => ($row['status'] === 'failed') ? 'high' : 'normal',
            'actionRequired' => ($row['status'] === 'failed'),
            'amount' => "N" . number_format($row['amount'])
        ];
    }

    // Return valid JSON
    echo json_encode([
        'success' => true,
        'data' => $transactions
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => 'General error: ' . $e->getMessage()
    ]);
}
?>
