<?php
// stripe_webhook.php

require_once 'config.php'; // Includi il file di configurazione con la connessione $pdo

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;

try {
    $event = \Stripe\Webhook::constructEvent(
        $payload, $sig_header, STRIPE_WEBHOOK_SECRET // Usa la costante definita in config.php
    );
} catch (\UnexpectedValueException $e) {
    http_response_code(400); exit();
} catch (\Stripe\Exception\SignatureVerificationException $e) {
    http_response_code(400); exit();
}

// Gestisci l'evento
switch ($event->type) {
    case 'account.updated':
        $account = $event->data->object;
        $stripeAccountId = $account->id;

        // Trova il tuo utente associato a questo account ID nel tuo DB
        $stmt = $pdo->prepare("SELECT user_id FROM stripe_accounts WHERE stripe_account_id = :stripe_account_id");
        $stmt->execute([':stripe_account_id' => $stripeAccountId]);
        $result = $stmt->fetch();

        if ($result) {
            $userId = $result['user_id'];

            $status = 'pending';
            if ($account->charges_enabled && $account->payouts_enabled) {
                $status = 'verified';
            } elseif (!empty($account->requirements->currently_due)) {
                $status = 'pending';
            } else {
                $status = 'under_review'; // Es. in attesa di revisione manuale di Stripe
            }

            // Aggiorna lo stato dell'account nel database
            $stmt = $pdo->prepare("UPDATE stripe_accounts SET
                                    status = :status,
                                    charges_enabled = :charges_enabled,
                                    payouts_enabled = :payouts_enabled,
                                    requirements_currently_due = :requirements_currently_due,
                                    updated_at = CURRENT_TIMESTAMP
                                  WHERE stripe_account_id = :stripe_account_id AND user_id = :user_id");
            $stmt->execute([
                ':status' => $status,
                ':charges_enabled' => $account->charges_enabled,
                ':payouts_enabled' => $account->payouts_enabled,
                ':requirements_currently_due' => json_encode($account->requirements->currently_due),
                ':stripe_account_id' => $stripeAccountId,
                ':user_id' => $userId
            ]);

            // Log per debugging
            error_log("Webhook 'account.updated' gestito per user_id: {$userId}, account_id: {$stripeAccountId}. Nuovo stato: {$status}.");

            // Puoi anche inviare email di notifica all'utente qui
            // notifyUser($userId, $status);

        } else {
            error_log("Webhook 'account.updated' ricevuto per account Stripe sconosciuto nel DB: " . $stripeAccountId);
        }
        break;
    default:
        error_log("Tipo di evento Stripe non gestito: " . $event->type);
}

http_response_code(200); // Sempre rispondere 200 OK
?>