<?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);
    
    $emailOrPhone = isset($input['emailOrPhone']) ? $input['emailOrPhone'] : null;
    
    $sql_ac=$pdo->prepare("SELECT *FROM users WHERE email='$emailOrPhone' || phone='$emailOrPhone'");
    $sql_ac->execute();
    
    $num_ac=$sql_ac->rowCount();
    
    if($num_ac==0){
		$num_acerr="user does not exist";
	}
	$fetch_ac=$sql_ac->fetch(PDO::FETCH_ASSOC);
	$account_no=$fetch_ac['account_no'];
	
    //$account_no   = isset($input['account_no']) ? $input['account_no'] : null;

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

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

    // === BUILD NOTIFICATIONS ARRAY ===
    $notifications = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $isSender   = ($row['fromAccount'] == $account_no);
        $isReceiver = ($row['toAccount'] == $account_no);

        // Determine type of notification
        if ($isSender) {
            $title = "You Sent Money";
            $message = "You sent ₦" . number_format($row['amount']) . " to " . $row['recipientName'] . " (" . $row['recipientBank'] . ")";
        } elseif ($isReceiver) {
            $title = "You Received Money";
            $message = "You received ₦" . number_format($row['amount']) . " from " . $row['senderName'] . " (" . $row['senderBank'] . ")";
        } else {
            $title = $row['status'] === 'success' ? 'Transaction Successful' : 'Transaction Update';
            $message = "₦" . number_format($row['amount']) . " transaction status: " . ucfirst($row['status']);
        }

        $notifications[] = [
            'id' => $row['id'],
            'emailOrPhone' => $row['emailOrPhone'],
            'transaction_ref' => $row['transaction_ref'],
            'title' => $title,
            'message' => $message,
            'type' => $isSender ? 'debit' : ($isReceiver ? 'credit' : 'transaction'),
            'timestamp' => $row['created_at'],
            'read' => false,
            'priority' => $row['status'] === 'failed' ? 'high' : 'normal',
            'actionRequired' => $row['status'] === 'failed',
            'amount' => "₦" . 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
?>
