<?php
// manage_merchant.php - Create and List Merchants
require_once 'config.php';

$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? null;

if ($action === 'create') {
    $name = $data['name'];
    $email = $data['email'];
    $callback = $data['callback'] ?? null;
    
    // Generate Secure Keys
    $api_key = "cv_" . bin2hex(random_bytes(8));
    $api_secret = "cv_sec_" . bin2hex(random_bytes(16));

    $res = supabase_request('POST', 'merchants', [
        'business_name' => $name,
        'email' => $email,
        'api_key' => $api_key,
        'api_secret' => $api_secret,
        'callback_url' => $callback
    ]);

    if ($res['status'] == 201) {
        echo json_encode([
            'status' => 'success',
            'api_key' => $api_key,
            'api_secret' => $api_secret
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to create merchant']);
    }

} elseif ($action === 'list') {
    $res = supabase_request('GET', 'merchants?order=created_at.desc');
    echo json_encode(['status' => 'success', 'data' => $res['data']]);
}
?>
