<?php
// includes/config.php - Complete Configuration File
// Version: Ready-to-Use

// ============================================
// SESSION START
// ============================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// DATABASE CONFIGURATION
// ============================================
define('DB_HOST', 'localhost');
define('DB_NAME', 'onesbd_LMS');           // Your database name
define('DB_USER', 'onesbd_LMS');           // Your database username
define('DB_PASS', 'onesbd_LMS');   // Your database password

// ============================================
// SITE CONFIGURATION
// ============================================
define('BASE_URL', 'https://onesbd.com/LMS/');
define('SITE_NAME', 'Ones BD  LMS');
define('SITE_EMAIL', 'admin@banglalms.com');
define('ADMIN_EMAIL', 'admin@banglalms.com');

// ============================================
// TIMEZONE
// ============================================
date_default_timezone_set('Asia/Dhaka');

// ============================================
// ERROR REPORTING
// ============================================
// Set to 0 on production, 1 for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);      // Change to 1 only for debugging
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../error.log');

// ============================================
// DATABASE CONNECTION
// ============================================
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::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
            PDO::ATTR_EMULATE_PREPARES => false,
        ]
    );
} catch(PDOException $e) {
    error_log("Database Connection Error: " . $e->getMessage());
    die("ডাটাবেস কানেকশন ত্রুটি। অনুগ্রহ করে config.php চেক করুন।");
}

// ============================================
// HELPER FUNCTIONS
// ============================================

/**
 * Check if user is logged in
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Get user data by ID
 */
function getUserData($pdo, $user_id) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        // Set default values for null fields to prevent errors
        if($user) {
            $user['full_name'] = $user['full_name'] ?? '';
            $user['email'] = $user['email'] ?? '';
            $user['phone'] = $user['phone'] ?? '';
            $user['bio'] = $user['bio'] ?? '';
            $user['avatar'] = $user['avatar'] ?? 'default-avatar.png';
            $user['role'] = $user['role'] ?? 'student';
            $user['status'] = $user['status'] ?? 'active';
            $user['admin_notes'] = $user['admin_notes'] ?? '';
            $user['google_id'] = $user['google_id'] ?? '';
            $user['google_email'] = $user['google_email'] ?? '';
            $user['phone_verified'] = $user['phone_verified'] ?? 0;
            $user['remember_token'] = $user['remember_token'] ?? '';
            $user['last_login'] = $user['last_login'] ?? null;
            $user['created_at'] = $user['created_at'] ?? date('Y-m-d H:i:s');
        }
        
        return $user;
    } catch(PDOException $e) {
        error_log("getUserData Error: " . $e->getMessage());
        return null;
    }
}

/**
 * Extract YouTube video ID from URL
 */
function getYouTubeId($url) {
    if(empty($url)) return null;
    
    $pattern = '/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/';
    preg_match($pattern, $url, $matches);
    
    return $matches[1] ?? null;
}

/**
 * Get YouTube thumbnail URL
 */
function getYouTubeThumbnail($url, $quality = 'maxresdefault') {
    $video_id = getYouTubeId($url);
    if(!$video_id) return null;
    
    return "https://img.youtube.com/vi/{$video_id}/{$quality}.jpg";
}

/**
 * Check if user is enrolled in a course
 */
function isEnrolled($pdo, $course_id, $user_id) {
    if(!isset($_SESSION['user_id'])) return false;
    
    try {
        // Check direct enrollment
        $stmt = $pdo->prepare("
            SELECT COUNT(*) FROM enrollments 
            WHERE user_id = ? AND course_id = ? AND payment_status = 'completed'
            AND (expires_at IS NULL OR expires_at >= CURDATE())
        ");
        $stmt->execute([$user_id, $course_id]);
        if($stmt->fetchColumn() > 0) return true;
        
        // Check package enrollment
        $stmt = $pdo->prepare("
            SELECT COUNT(*) FROM enrollments e
            JOIN package_courses pc ON e.package_id = pc.package_id
            WHERE e.user_id = ? AND pc.course_id = ? AND e.payment_status = 'completed'
            AND (e.expires_at IS NULL OR e.expires_at >= CURDATE())
        ");
        $stmt->execute([$user_id, $course_id]);
        return $stmt->fetchColumn() > 0;
        
    } catch(PDOException $e) {
        error_log("isEnrolled Error: " . $e->getMessage());
        return false;
    }
}

/**
 * Get user progress for a course
 */
function getUserProgress($pdo, $course_id, $user_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                COUNT(DISTINCT l.id) as total_lessons,
                COUNT(DISTINCT CASE WHEN lp.completed = 1 THEN lp.lesson_id END) as completed_lessons
            FROM lessons l
            LEFT JOIN lesson_progress lp ON l.id = lp.lesson_id AND lp.user_id = ?
            WHERE l.course_id = ?
        ");
        $stmt->execute([$user_id, $course_id]);
        $result = $stmt->fetch();
        
        return [
            'total_lessons' => (int)($result['total_lessons'] ?? 0),
            'completed_lessons' => (int)($result['completed_lessons'] ?? 0),
            'percentage' => ($result['total_lessons'] > 0) 
                ? round(($result['completed_lessons'] / $result['total_lessons']) * 100) 
                : 0
        ];
    } catch(PDOException $e) {
        error_log("getUserProgress Error: " . $e->getMessage());
        return ['total_lessons' => 0, 'completed_lessons' => 0, 'percentage' => 0];
    }
}

/**
 * Create URL-friendly slug
 */
function createSlug($string) {
    // Transliterate Bengali characters
    $translit = [
        'অ'=>'a','আ'=>'a','ই'=>'i','ঈ'=>'i','উ'=>'u','ঊ'=>'u',
        'এ'=>'e','ঐ'=>'oi','ও'=>'o','ঔ'=>'ou',
        'ক'=>'k','খ'=>'kh','গ'=>'g','ঘ'=>'gh','ঙ'=>'ng',
        'চ'=>'c','ছ'=>'ch','জ'=>'j','ঝ'=>'jh','ঞ'=>'n',
        'ট'=>'t','ঠ'=>'th','ড'=>'d','ঢ'=>'dh','ণ'=>'n',
        'ত'=>'t','থ'=>'th','দ'=>'d','ধ'=>'dh','ন'=>'n',
        'প'=>'p','ফ'=>'ph','ব'=>'b','ভ'=>'bh','ম'=>'m',
        'য'=>'j','র'=>'r','ল'=>'l','শ'=>'sh','ষ'=>'sh',
        'স'=>'s','হ'=>'h','ড়'=>'r','ঢ়'=>'rh','য়'=>'y',
        'ৎ'=>'t','ং'=>'ng','ঃ'=>'h','ঁ'=>'n','া'=>'a',
        'ি'=>'i','ী'=>'i','ু'=>'u','ূ'=>'u','ে'=>'e',
        'ৈ'=>'oi','ো'=>'o','ৌ'=>'ou','ক'=>'k'
    ];
    
    $string = str_replace(array_keys($translit), array_values($translit), $string);
    $string = strtolower(trim($string));
    $string = preg_replace('/[^a-z0-9\s-]/', '', $string);
    $string = preg_replace('/[\s_]+/', '-', $string);
    $string = preg_replace('/-+/', '-', $string);
    
    return trim($string, '-');
}

/**
 * Sanitize output for HTML display
 */
function h($string) {
    return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}

/**
 * Format price in Bangladeshi Taka
 */
function formatPrice($amount) {
    return '৳' . number_format((float)$amount, 0);
}

/**
 * Format date in Bengali
 */
function formatDate($date, $format = 'd F Y') {
    $timestamp = is_numeric($date) ? $date : strtotime($date);
    
    $months = [
        'January' => 'জানুয়ারি', 'February' => 'ফেব্রুয়ারি', 'March' => 'মার্চ',
        'April' => 'এপ্রিল', 'May' => 'মে', 'June' => 'জুন',
        'July' => 'জুলাই', 'August' => 'আগস্ট', 'September' => 'সেপ্টেম্বর',
        'October' => 'অক্টোবর', 'November' => 'নভেম্বর', 'December' => 'ডিসেম্বর'
    ];
    
    $formatted = date($format, $timestamp);
    return str_replace(array_keys($months), array_values($months), $formatted);
}


/**
 * Get time ago in Bengali
 */
function timeAgo($datetime) {
    $timestamp = is_numeric($datetime) ? $datetime : strtotime($datetime);
    $diff = time() - $timestamp;
    
    if($diff < 60) return 'এইমাত্র';
    if($diff < 3600) return floor($diff / 60) . ' মিনিট আগে';
    if($diff < 86400) return floor($diff / 3600) . ' ঘন্টা আগে';
    if($diff < 2592000) return floor($diff / 86400) . ' দিন আগে';
    if($diff < 31536000) return floor($diff / 2592000) . ' মাস আগে';
    return floor($diff / 31536000) . ' বছর আগে';
}

/**
 * Get current user data
 */
function currentUser($pdo) {
    if(!isLoggedIn()) return null;
    return getUserData($pdo, $_SESSION['user_id']);
}

/**
 * Check if current user is admin
 */
function isAdmin() {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'admin';
}

/**
 * Redirect with message
 */
function redirect($url, $message = '', $type = 'info') {
    if($message) {
        $_SESSION['message'] = $message;
        $_SESSION['message_type'] = $type;
    }
    header('Location: ' . $url);
    exit;
}

/**
 * Display flash message
 */
function showMessage() {
    if(isset($_SESSION['message'])) {
        $type = $_SESSION['message_type'] ?? 'info';
        $message = $_SESSION['message'];
        unset($_SESSION['message'], $_SESSION['message_type']);
        
        return "<div class='alert alert-{$type} alert-dismissible fade show rounded-pill'>
                    {$message}
                    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                </div>";
    }
    return '';
}

/**
 * Validate CSRF Token
 */
function generateCSRFToken() {
    if(!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    if(!isset($_SESSION['csrf_token']) || empty($token)) return false;
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Upload file
 */
function uploadFile($file, $destination, $allowed_types = ['jpg','jpeg','png','gif','webp']) {
    if(!$file || $file['error'] != 0) return false;
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if(!in_array($ext, $allowed_types)) return false;
    
    if(!is_dir($destination)) {
        mkdir($destination, 0755, true);
    }
    
    $filename = time() . '_' . uniqid() . '.' . $ext;
    $filepath = $destination . '/' . $filename;
    
    if(move_uploaded_file($file['tmp_name'], $filepath)) {
        return $filename;
    }
    
    return false;
}
// Add at the end of includes/config.php

/**
 * Get site setting value
 */
function getSetting($pdo, $key, $default = '') {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM site_settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        return $result ? $result['setting_value'] : $default;
    } catch(PDOException $e) {
        return $default;
    }
}

/**
 * Display dynamic logo
 */
function displayLogo($pdo) {
    $use_image = getSetting($pdo, 'use_image_logo', '0');
    $logo_image = getSetting($pdo, 'logo_image', '');
    $logo_text = getSetting($pdo, 'logo_text', 'বাংলা LMS');
    $logo_icon = getSetting($pdo, 'logo_icon', 'fa-graduation-cap');
    $site_title = getSetting($pdo, 'site_title', 'বাংলা LMS');
    
    if($use_image == '1' && !empty($logo_image) && file_exists('uploads/logo/' . $logo_image)) {
        return '<img src="uploads/logo/' . $logo_image . '" alt="' . htmlspecialchars($site_title) . '" style="height:40px;">';
    } else {
        return '<i class="fas ' . $logo_icon . ' me-2"></i>' . htmlspecialchars($logo_text);
    }
}

/**
 * Get site title
 */
function getSiteTitle($pdo) {
    return getSetting($pdo, 'site_title', 'বাংলা LMS');
}
/**
 * Debug function (remove in production)
 */
function debug($data) {
    echo '<pre style="background:#f4f4f4;padding:10px;border-radius:5px;">';
    print_r($data);
    echo '</pre>';
}
?>