<?php
/**
 * PAKClub Admin Panel - Configuration
 * Database and application settings
 */

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'luckrgur_HACK');
define('DB_USER', 'luckrgur_HACK');
define('DB_PASS', 'luckrgur_HACK');

// Admin Credentials
define('ADMIN_USERNAME', 'Raz1122');
define('ADMIN_PASSWORD', 'ir1122');

// Session Configuration
define('SESSION_NAME', 'PAKCLUB_ADMIN_SESSION');
define('SESSION_LIFETIME', 86400); // 24 hours

// Upload Configuration
define('UPLOAD_DIR', __DIR__ . '/uploads/logos/');
define('AUDIO_UPLOAD_DIR', __DIR__ . '/uploads/audios/');
define('MAX_UPLOAD_SIZE', 5 * 1024 * 1024); // 5MB
define('MAX_AUDIO_SIZE', 10 * 1024 * 1024); // 10MB
define('ALLOWED_EXTENSIONS', ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']);
define('ALLOWED_AUDIO_EXTENSIONS', ['mp3', 'wav', 'ogg', 'aac', 'm4a']);

// Application Version
define('APP_VERSION', '2.0.0');
define('APP_NAME', 'PAKClub Admin');

// Timezone
date_default_timezone_set('Asia/Karachi');

// Error Reporting (set to 0 in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

/**
 * Database connection singleton
 */
function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $pdo = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        } catch (PDOException $e) {
            http_response_code(500);
            die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
        }
    }
    return $pdo;
}

/**
 * Get a setting value from the database
 */
function getSetting($key, $default = '') {
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        return $result ? $result['setting_value'] : $default;
    } catch (Exception $e) {
        return $default;
    }
}

/**
 * Set a setting value in the database
 */
function setSetting($key, $value) {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO settings (setting_key, setting_value, updated_at) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()");
    return $stmt->execute([$key, $value]);
}

/**
 * Build the full refer link using the main domain or app domain
 */
function buildReferLink($referPath, $appDomain = '') {
    $mainDomain = getSetting('main_domain', '');
    $domainToUse = !empty($appDomain) ? $appDomain : $mainDomain;
    
    if (empty($domainToUse)) return $referPath;
    
    // Remove trailing slash from domain
    $domainToUse = rtrim($domainToUse, '/');
    
    // Ensure https://
    if (!preg_match('/^https?:\/\//', $domainToUse)) {
        $domainToUse = 'https://' . $domainToUse;
    }
    
    // Ensure refer path starts with /
    if (!empty($referPath) && $referPath[0] !== '/') {
        $referPath = '/' . $referPath;
    }
    
    return $domainToUse . $referPath;
}

/**
 * Get the base URL for uploaded files
 */
function getUploadBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $basePath = dirname($_SERVER['SCRIPT_NAME']);
    $basePath = str_replace(['/endpoint', '/ir-admin', '\\endpoint', '\\ir-admin'], '', $basePath);
    $basePath = rtrim($basePath, '/\\');
    return $protocol . '://' . $host . $basePath . '/uploads/logos/';
}

/**
 * Get the base URL for uploaded audio files
 */
function getAudioBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $basePath = dirname($_SERVER['SCRIPT_NAME']);
    $basePath = str_replace(['/endpoint', '/ir-admin', '\\endpoint', '\\ir-admin'], '', $basePath);
    $basePath = rtrim($basePath, '/\\');
    return $protocol . '://' . $host . $basePath . '/uploads/audios/';
}
