<?php
require_once __DIR__ . '/config.php';

// Main Database Connection Function
function db(): PDO {
    static $pdo = null;
    if ($pdo) return $pdo;

    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
    $opt = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    
    try {
        $pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);
    } catch (PDOException $e) {
        die("Database Connection Failed: " . $e->getMessage());
    }

    // Optional: Schema check (Keep your existing logic here if needed)
    try {
        $stmt = $pdo->prepare("SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'subscriptions' AND COLUMN_NAME = 'start_date'");
        $stmt->execute([DB_NAME]);
        if ($stmt->fetchColumn() === 'date') {
            $pdo->exec("ALTER TABLE subscriptions MODIFY start_date DATETIME NOT NULL");
        }
    } catch (Throwable $e) {
        // Ignore schema errors to prevent app blocking
    }

    return $pdo;
}

// ✅ Execute a query (Insert, Update, Delete)
function query(string $sql, array $params = []) {
    try {
        $stmt = db()->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    } catch (Exception $e) {
        die("Query Failed: " . $e->getMessage());
    }
}

// ✅ Fetch ALL rows (For Lists)
function all_rows(string $sql, array $params = []) {
    return query($sql, $params)->fetchAll();
}

// ✅ Fetch ONE row (For Edit, View, Login)
// This fixes the 'row()' error by using the correct db() connection
function row(string $sql, array $params = []) {
    return query($sql, $params)->fetch();
}

// Alias 'one' to 'row' in case you used 'one()' elsewhere
function one(string $sql, array $params = []) {
    return row($sql, $params);
}

// ✅ Get Last Inserted ID
function last_id() {
    return db()->lastInsertId();
}
?>