<?php
ob_start(); // Prevent accidental whitespace before JSON output

// === HEADERS ===
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

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

// === ERROR SETTINGS (optional for cleaner JSON) ===
error_reporting(0);
ini_set('display_errors', 0);

// === DATABASE CONNECTION ===
require("dbcon.php");

try {
    // === GET JSON INPUT ===
    $input = json_decode(file_get_contents("php://input"), true);
   // Backward-compatible check (no ?? operator)
    $emailOrPhone = isset($input['emailOrPhone']) ? $input['emailOrPhone'] : null;

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

    // === PREPARE AND EXECUTE QUERY ===
    $stmt = $pdo->prepare("
        SELECT 
		*FROM notifications 
        WHERE emailOrPhone = :emailOrPhone 
        ORDER BY created_at DESC
    ");
    $stmt->bindParam(":emailOrPhone", $emailOrPhone);
    $stmt->execute();

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

    // === RETURN SUCCESS RESPONSE ===
    echo json_encode([
        'success' => true,
        'data' => $notifications
    ]);

} catch (PDOException $e) {
    // === DATABASE ERROR RESPONSE ===
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}

ob_end_flush(); // Ensure clean JSON output
?>
