<?php
session_start();

// ============================================
// DATABASE CONFIGURATION - CHANGE THESE VALUES
// ============================================
define('DB_HOST', 'localhost');
define('DB_NAME', 'onesbd_LMS');     // Your database name from cPanel
define('DB_USER', 'onesbd_LMS');     // Your database username from cPanel
define('DB_PASS', 'onesbd_LMS');  // Your database password

// Site URL
define('BASE_URL', 'https://onesbd.com/LMS/');

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

// Error reporting (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 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"
        ]
    );
} catch(PDOException $e) {
    die("ডাটাবেস কানেকশন ত্রুটি: " . $e->getMessage());
}

// Helper Functions
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function getUserData($pdo, $user_id) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    return $stmt->fetch();
}

function getYouTubeId($url) {
    if(empty($url)) return null;
    preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)/', $url, $matches);
    return isset($matches[1]) ? $matches[1] : null;
}

function isEnrolled($pdo, $course_id, $user_id) {
    if (!isLoggedIn()) return false;
    
    // 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;
}

function getUserProgress($pdo, $course_id, $user_id) {
    $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]);
    return $stmt->fetch();
}
?>