<?php
// initiate_custom_onboarding.php

require_once 'config.php'; // Includi il file di configurazione con la connessione $pdo

header('Content-Type: application/json');

try {
    $userId = $_GET['user_id'] ?? null;

    if (!$userId) {
        throw new Exception("ID utente non fornito.");
    }

    // 1. Recupera l'email e i dettagli dell'utente dal tuo database
    $stmt = $pdo->prepare("SELECT email, name FROM users WHERE id = :user_id");
    $stmt->execute([':user_id' => $userId]);
    $user = $stmt->fetch();

    if (!$user) {
        throw new Exception("Utente non trovato.");
    }

    $userEmail = $user['email'];
    $userName = $user['name']; // Potresti voler usare il nome per pre-compilare i dettagli dell'account Stripe

    // 2. Crea il Custom Account Stripe
    $account = \Stripe\Account::create([
        'type' => 'custom',
        'country' => 'IT',
        'email' => $userEmail,
        'capabilities' => [
            'card_payments' => ['requested' => true],
            'transfers' => ['requested' => true],
            'sepa_debit_payments' => ['requested' => true],
        ],
        'business_profile' => [
            'mcc' => '5734',
            'url' => YOUR_PLATFORM_URL . '/users/' . $userId,
            'product_description' => 'Servizi della piattaforma per ' . $userName,
        ],
        'tos_acceptance' => [
            'date' => time(),
            'ip' => $_SERVER['REMOTE_ADDR'],
        ],
    ]);

    $newAccountId = $account->id;

    // 3. AGGIORNA IL TUO DATABASE
    // Disabilita il vecchio account Express (se esiste e se lo trovi)
    $stmt = $pdo->prepare("UPDATE stripe_accounts SET is_active = FALSE, status = 'migrated' WHERE user_id = :user_id AND is_active = TRUE AND account_type = 'express'");
    $stmt->execute([':user_id' => $userId]);

    // Inserisci il nuovo Custom Account nel tuo database e impostalo come attivo
    $stmt = $pdo->prepare("INSERT INTO stripe_accounts (user_id, stripe_account_id, account_type, status, charges_enabled, payouts_enabled, is_active) VALUES (:user_id, :stripe_account_id, :account_type, :status, :charges_enabled, :payouts_enabled, :is_active)");
    $stmt->execute([
        ':user_id' => $userId,
        ':stripe_account_id' => $newAccountId,
        ':account_type' => 'custom',
        ':status' => 'pending', // Inizialmente in pending
        ':charges_enabled' => $account->charges_enabled,
        ':payouts_enabled' => $account->payouts_enabled,
        ':is_active' => TRUE
    ]);

    // 4. Genera l'AccountLink e reindirizza
    $account_link = \Stripe\AccountLink::create([
        'account' => $newAccountId,
        'refresh_url' => YOUR_PLATFORM_URL . '/stripe_onboarding_refresh.php?account_id=' . $newAccountId . '&user_id=' . $userId,
        'return_url' => YOUR_PLATFORM_URL . '/stripe_onboarding_return.php?account_id=' . $newAccountId . '&user_id=' . $userId,
        'type' => 'account_onboarding',
        'collection_options' => [
            'fields' => 'currently_due',
            'future_requirements' => 'include',
        ],
    ]);

    header("Location: " . $account_link->url);
    exit();

} catch (\Stripe\Exception\ApiErrorException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Errore Stripe: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Errore generico: ' . $e->getMessage()]);
}
?>