<?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);

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

    $emailOrPhone = isset($input['emailOrPhone']) ? trim($input['emailOrPhone']) : null;
    //$account_no = isset($input['account_no']) ? trim($input['account_no']) : 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'];

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

    // Fetch all related transactions (sender or receiver)
    $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 
            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();

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

    $transactions = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $isSent = ($row['fromAccount'] === $account_no);
        $isReceived = ($row['toAccount'] === $account_no);

        // Determine title & message type
        if ($isSent) {
            $title = ($row['status'] === 'success') ? 'Money Sent Successfully' : 'Transaction Failed';
            $message = "₦" . number_format($row['amount']) . " sent to " . $row['recipientName'] . " (" . $row['recipientBank'] . ")";
            $transType = "debit";
        } elseif ($isReceived) {
            $title = ($row['status'] === 'success') ? 'Money Received' : 'Transaction Pending';
            $message = "₦" . number_format($row['amount']) . " received from " . $row['recipientName'];
            $transType = "credit";
        } else {
            $title = "Transaction Update";
            $message = "₦" . number_format($row['amount']) . " transaction processed.";
            $transType = $row['type'];
        }

        $transactions[] = [
            'transaction_ref' => $row['transaction_ref'],
            'emailOrPhone' => $row['emailOrPhone'],
            'title' => $title,
            'message' => $message,
            'type' => $transType,
            'timestamp' => $row['created_at'],
            'status' => $row['status'],
            'balance_before' => "₦" . number_format($row['balance_before']),
            'balance_after' => "₦" . number_format($row['balance_after']),
            'recipientName' => $row['recipientName'],
            'recipientBank' => $row['recipientBank'],
            'amount' => number_format($row['amount']),
            'note' => $row['note'],
            'read' => false,
            'priority' => ($row['status'] === 'failed') ? 'high' : 'normal',
            'actionRequired' => ($row['status'] === 'failed')
        ];
    }

    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()]);
}
?>
