<?php

declare(strict_types=1);

function getPdo(): PDO
{
    static $pdo = null;

    // 🎀 Reutilise la connexion PDO pour eviter les reconnexions inutiles 🎀
    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $database = 'mindgallery';

    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    // 🎀 Configurations MAMP courantes testees automatiquement 🎀
    $candidates = [
        ['host' => '127.0.0.1', 'port' => 3306, 'user' => 'root', 'pass' => 'root'],
        ['host' => '127.0.0.1', 'port' => 3306, 'user' => 'root', 'pass' => ''],
        ['host' => 'localhost', 'port' => 3306, 'user' => 'root', 'pass' => 'root'],
        ['host' => 'localhost', 'port' => 3306, 'user' => 'root', 'pass' => ''],
        ['host' => '127.0.0.1', 'port' => 8889, 'user' => 'root', 'pass' => 'root'],
        ['host' => '127.0.0.1', 'port' => 8889, 'user' => 'root', 'pass' => ''],
    ];

    $serverPdo = null;
    $active = null;

    foreach ($candidates as $candidate) {
        try {
            // 🎀 Test de connexion serveur MySQL sans base cible 🎀
            $serverDsn = 'mysql:host=' . $candidate['host'] . ';port=' . $candidate['port'] . ';charset=utf8mb4';
            $serverPdo = new PDO($serverDsn, $candidate['user'], $candidate['pass'], $options);
            $active = $candidate;
            break;
        } catch (PDOException $e) {
            continue;
        }
    }

    if (!$serverPdo || !$active) {
        throw new RuntimeException('Impossible de se connecter a MySQL. Verifie que MySQL MAMP est demarre et que le compte root est configure.');
    }

    // 🎀 Creation automatique de la base si elle n'existe pas 🎀
    $serverPdo->exec("CREATE DATABASE IF NOT EXISTS `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

    $dbDsn = 'mysql:host=' . $active['host'] . ';port=' . $active['port'] . ';dbname=' . $database . ';charset=utf8mb4';
    $pdo = new PDO($dbDsn, $active['user'], $active['pass'], $options);

    // 🎀 Creation automatique de la table users au premier lancement 🎀
    $pdo->exec(
        "CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            email VARCHAR(190) NOT NULL UNIQUE,
            password_hash VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );

    return $pdo;
}
