<?php
/**
 * Dirt Track Masters - Global Configuration
 */
session_start();

// ── Site Constants ──────────────────────────────────────────────────────────────
define('SITE_NAME', 'Dirt Track Masters');
define('SITE_URL',  'https://dirttrackmasters.com');
define('SITE_EMAIL','parts@dirttrackmasters.com');
define('SITE_PHONE','1-800-DIRT-BIKE');

// ── SMTP ────────────────────────────────────────────────────────────────────────
define('SMTP_HOST', 'cpanel12.v-sys.org');
define('SMTP_PORT', 465);
define('SMTP_USER', 'parts@dirttrackmasters.com');
define('SMTP_PASS', 'Goldbars1!');
define('SMTP_ENC',  'ssl');

// ── Database (SQLite) ───────────────────────────────────────────────────────────
function getDB(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dbPath = __DIR__ . '/../database/database.sqlite';
        $pdo = new PDO('sqlite:' . $dbPath, null, null, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    }
    return $pdo;
}

// ── Helpers ─────────────────────────────────────────────────────────────────────
function e(string $val): string {
    return htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
}

function asset(string $path): string {
    return '/' . ltrim($path, '/');
}

function siteUrl(string $path = ''): string {
    return SITE_URL . '/' . ltrim($path, '/');
}

function currentUrl(): string {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    return $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

function cartCount(): int {
    return isset($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
}

// ── Data Fetchers ───────────────────────────────────────────────────────────────
function getAllBrands(): array {
    return getDB()->query("SELECT * FROM brands ORDER BY name")->fetchAll();
}

function getAllCategories(): array {
    return getDB()->query("SELECT * FROM categories ORDER BY name")->fetchAll();
}

function getAllYears(): array {
    return getDB()->query("SELECT * FROM years ORDER BY year DESC")->fetchAll();
}

function getAllModels(): array {
    return getDB()->query("
        SELECT m.*, b.name as brand_name, b.slug as brand_slug
        FROM models m
        JOIN brands b ON m.brand_id = b.id
        ORDER BY b.name, m.name
    ")->fetchAll();
}

function getProductBySlug(string $slug): ?array {
    $stmt = getDB()->prepare("
        SELECT p.*, c.name as category_name, c.slug as category_slug,
               b.name as brand_name, b.slug as brand_slug
        FROM products p
        JOIN categories c ON p.category_id = c.id
        JOIN brands b ON p.brand_id = b.id
        WHERE p.slug = ?
    ");
    $stmt->execute([$slug]);
    $product = $stmt->fetch();
    return $product ?: null;
}

function getProductFitments(int $productId): array {
    return getDB()->query("
        SELECT y.year, m.name as model_name, b.name as brand_name
        FROM product_fitments pf
        JOIN model_year my ON pf.model_year_id = my.id
        JOIN years y ON my.year_id = y.id
        JOIN models m ON my.model_id = m.id
        JOIN brands b ON m.brand_id = b.id
        WHERE pf.product_id = {$productId}
        ORDER BY y.year DESC, b.name, m.name
    ")->fetchAll();
}

function getProducts(array $filters = [], int $limit = 0): array {
    $sql = "SELECT p.*, c.name as category_name, c.slug as category_slug,
                   b.name as brand_name, b.slug as brand_slug
            FROM products p
            JOIN categories c ON p.category_id = c.id
            JOIN brands b ON p.brand_id = b.id";
    $params = [];
    $wheres = [];

    if (!empty($filters['category_slug'])) {
        $wheres[] = "c.slug = ?";
        $params[] = $filters['category_slug'];
    }
    if (!empty($filters['brand_slug'])) {
        $wheres[] = "b.slug = ?";
        $params[] = $filters['brand_slug'];
    }
    if (!empty($filters['year']) && !empty($filters['make']) && !empty($filters['model'])) {
        $sql .= " JOIN product_fitments pf ON pf.product_id = p.id
                  JOIN model_year my ON pf.model_year_id = my.id
                  JOIN years y ON my.year_id = y.id
                  JOIN models mo ON my.model_id = mo.id
                  JOIN brands bm ON mo.brand_id = bm.id";
        $wheres[] = "y.year = ?";
        $params[] = $filters['year'];
        $wheres[] = "bm.slug = ?";
        $params[] = $filters['make'];
        $wheres[] = "mo.slug = ?";
        $params[] = $filters['model'];
    }

    if ($wheres) {
        $sql .= " WHERE " . implode(' AND ', $wheres);
    }
    $sql .= " GROUP BY p.id ORDER BY p.name";
    if ($limit > 0) {
        $sql .= " LIMIT " . (int)$limit;
    }

    $stmt = getDB()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function getCategoryBySlug(string $slug): ?array {
    $stmt = getDB()->prepare("SELECT * FROM categories WHERE slug = ?");
    $stmt->execute([$slug]);
    return $stmt->fetch() ?: null;
}

function getBrandBySlug(string $slug): ?array {
    $stmt = getDB()->prepare("SELECT * FROM brands WHERE slug = ?");
    $stmt->execute([$slug]);
    return $stmt->fetch() ?: null;
}
