<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}


$tenantBaseUrl = '/' . basename(dirname(__DIR__));

if (defined('PUBLIC_PAGE') && PUBLIC_PAGE === true) {
    return;
}


if (
    isset($_SESSION['tenant']) &&
    $_SESSION['tenant']['statut'] === 'actif'
) {
    return;
}

require_once __DIR__ . '/../config/db_master.php';


$sub = basename(dirname(__DIR__));
$sub = str_replace('eagle_client_', '', $sub);


$stmt = $masterPdo->prepare("
    SELECT * 
    FROM clients_saas 
    WHERE subdomain = ?
    LIMIT 1
");
$stmt->execute([$sub]);
$client = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$client) {
    http_response_code(403);
    exit('Client SaaS inconnu');
}


if ($client['statut'] !== 'actif') {
    header("Location: {$tenantBaseUrl}/includes/access_denied.php");
    exit;
}

/* =========================================
   ABONNEMENT ACTIF
========================================= */
$stmt = $masterPdo->prepare("
    SELECT * 
    FROM abonnements_saas
    WHERE client_id = ?
      AND statut = 'actif'
      AND (date_fin IS NULL OR date_fin >= CURDATE())
    ORDER BY date_fin DESC
    LIMIT 1
");
$stmt->execute([$client['id']]);
$abo = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$abo) {
    header("Location: {$tenantBaseUrl}/includes/access_denied.php");
    exit;
}

/* =========================================
   FACTURES IMPAYÉES
========================================= */
$stmt = $masterPdo->prepare("
    SELECT id 
    FROM saas_factures
    WHERE client_id = ?
      AND statut != 'payé'
    LIMIT 1
");
$stmt->execute([$client['id']]);

if ($stmt->fetchColumn()) {
   header("Location: {$tenantBaseUrl}/includes/access_denied.php");
    exit;
}

/* =========================================
   TENANT VALIDÉ → MISE EN SESSION
========================================= */
$_SESSION['tenant'] = [
    'id'        => (int)$client['id'],
    'subdomain' => $client['subdomain'],
    'statut'    => $client['statut'],
    'abo_id'    => (int)$abo['id']
];

// À partir d’ici → accès AUTORISÉ
