<?php
// =============================================
// Database Configuration
// =============================================

define('DB_HOST', 'localhost');
define('DB_NAME', 'bismitri_electro_shop');
define('DB_USER', 'bismitri_electro_shop');
define('DB_PASS', '8;PZdi}M1}FTxD*x');
define('DB_CHARSET', 'utf8mb4');

// =============================================
// Site Configuration
// =============================================

define('SITE_URL', 'https://bismitrichy.com/bismi/');

// Upload directory path (relative to project root)
define('UPLOAD_DIR', __DIR__ . '/../uploads/products/');
define('UPLOAD_URL', SITE_URL . '/uploads/products/');

// =============================================
// Application Settings
// =============================================

// Max images per product
define('MAX_PRODUCT_IMAGES', 8);

// Max hero slider images
define('MAX_HERO_SLIDER_IMAGES', 3);

// Admin session name
define('ADMIN_SESSION', 'electro_admin_logged_in');

// =============================================
// Database Connection (PDO)
// =============================================
function getDB(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
            $options = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ];
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            die('<div style="font-family:sans-serif;padding:40px;color:red;"><h2>Database Connection Failed</h2><p>' . htmlspecialchars($e->getMessage()) . '</p><p>Please check your <strong>includes/config.php</strong> settings.</p></div>');
        }
    }
    return $pdo;
}

// =============================================
// Helper Functions
// =============================================

function getProducts(int $limit = 0, string $status = ''): array {
    $db = getDB();
    $sql = "SELECT p.*, (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY sort_order ASC LIMIT 1) AS main_image
            FROM products p";
    $params = [];
    if ($status) {
        $sql .= " WHERE p.selling_status = ?";
        $params[] = $status;
    }
    $sql .= " ORDER BY p.created_at DESC";
    if ($limit > 0) {
        $sql .= " LIMIT ?";
        $params[] = $limit;
    }
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function getProductById(int $id): ?array {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$id]);
    $product = $stmt->fetch();
    if (!$product) return null;

    // Get images
    $imgStmt = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order ASC");
    $imgStmt->execute([$id]);
    $product['images'] = $imgStmt->fetchAll();

    return $product;
}

function getProductImages(int $productId): array {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order ASC");
    $stmt->execute([$productId]);
    return $stmt->fetchAll();
}

function getRandomPhone(): ?array {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM contact_numbers WHERE is_active = 1 ORDER BY RAND() LIMIT 1");
    $stmt->execute();
    return $stmt->fetch() ?: null;
}

function getAllPhones(): array {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM contact_numbers ORDER BY id ASC");
    $stmt->execute();
    return $stmt->fetchAll();
}

function getSetting(string $key): string {
    $db = getDB();
    $stmt = $db->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch();
    return $row ? $row['setting_value'] : '';
}

function saveSetting(string $key, string $value): void {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $stmt->execute([$key, $value]);
}

function getJsonSetting(string $key, array $default = []): array {
    $value = getSetting($key);
    $data = json_decode($value, true);
    return is_array($data) ? $data : $default;
}

function formatPrice(float $price): string {
    return '₹' . number_format($price, 2);
}

function getStatusBadge(string $status): string {
    $map = [
        'available'    => '<span class="badge bg-success">Available</span>',
        'out_of_stock' => '<span class="badge bg-danger">Out of Stock</span>',
        'coming_soon'  => '<span class="badge bg-warning text-dark">Coming Soon</span>',
    ];
    return $map[$status] ?? '<span class="badge bg-secondary">' . ucfirst($status) . '</span>';
}

function isAdminLoggedIn(): bool {
    if (session_status() === PHP_SESSION_NONE) session_start();
    return !empty($_SESSION[ADMIN_SESSION]);
}

function requireAdminLogin(): void {
    if (!isAdminLoggedIn()) {
        header('Location: ' . SITE_URL . '/admin/login.php');
        exit;
    }
}

function sanitize(string $str): string {
    return htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8');
}

function getProductUrl(int $id): string {
    return SITE_URL . '/product.php?id=' . $id;
}

function buildWhatsAppLink(array $product, string $waNumber): string {
    $template = getSetting('whatsapp_message_template');
    $message = str_replace(
        ['{product_name}', '{price}', '{product_link}'],
        [$product['name'], number_format($product['price'], 2), getProductUrl($product['id'])],
        $template
    );
    return 'https://wa.me/' . preg_replace('/\D/', '', $waNumber) . '?text=' . urlencode($message);
}
