<?php
// admin/live-classes.php - Live Class Management with Zoom/GMeet Config
session_start();
require_once '../includes/config.php';
require_once '../includes/sms_config.php';

if(!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'instructor')) {
    header('Location: ../auth.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'];
$message = '';
$msg_type = 'info';

// ==================== SAVE ZOOM/GMEET CONFIG (Admin Only) ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_config']) && $user_role == 'admin') {
    $zoom_api_key = trim($_POST['zoom_api_key'] ?? '');
    $zoom_api_secret = trim($_POST['zoom_api_secret'] ?? '');
    $zoom_default_link = trim($_POST['zoom_default_link'] ?? '');
    $gmeet_default_link = trim($_POST['gmeet_default_link'] ?? '');
    $default_platform = $_POST['default_platform'] ?? 'gmeet';
    
    // Save to a config file or database
    $config_data = [
        'zoom_api_key' => $zoom_api_key,
        'zoom_api_secret' => $zoom_api_secret,
        'zoom_default_link' => $zoom_default_link,
        'gmeet_default_link' => $gmeet_default_link,
        'default_platform' => $default_platform,
    ];
    
    file_put_contents('../includes/live_config.json', json_encode($config_data, JSON_PRETTY_PRINT));
    
    $message = '✅ কনফিগারেশন সংরক্ষিত হয়েছে!';
    $msg_type = 'success';
}

// ==================== CREATE LIVE CLASS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_class'])) {
    $course_id = $_POST['course_id'] ?: null;
    $title_bn = trim($_POST['title_bn']);
    $title_en = trim($_POST['title_en'] ?? '');
    $platform = $_POST['platform'] ?? 'gmeet';
    $meeting_link = trim($_POST['meeting_link']);
    $meeting_id = trim($_POST['meeting_id'] ?? '');
    $meeting_password = trim($_POST['meeting_password'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $scheduled_at = $_POST['scheduled_at'];
    $duration = (int)$_POST['duration'];
    $send_sms_before = (int)$_POST['send_sms_before'];
    
    if(empty($title_bn) || empty($meeting_link) || empty($scheduled_at)) {
        $message = 'টাইটেল, মিটিং লিংক এবং সময় প্রয়োজন';
        $msg_type = 'danger';
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO live_classes (course_id, instructor_id, title_bn, title_en, platform, meeting_link, meeting_id, meeting_password, description, scheduled_at, duration_minutes, send_sms_before) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$course_id, $user_id, $title_bn, $title_en, $platform, $meeting_link, $meeting_id, $meeting_password, $description, $scheduled_at, $duration, $send_sms_before]);
        
        $class_id = $pdo->lastInsertId();
        
        // Schedule SMS
        if($send_sms_before > 0 && $course_id) {
            $sms_scheduled_time = date('Y-m-d H:i:s', strtotime($scheduled_at) - ($send_sms_before * 60));
            $course = $pdo->prepare("SELECT title_bn FROM courses WHERE id = ?");
            $course->execute([$course_id]);
            $course_name = $course->fetchColumn() ?: 'কোর্স';
            
            $sms_message = "🔴 লাইভ ক্লাস রিমাইন্ডার!\n\nকোর্স: $course_name\nক্লাস: $title_bn\nসময়: " . date('d/m/Y h:i A', strtotime($scheduled_at)) . "\nপ্ল্যাটফর্ম: " . strtoupper($platform) . "\nলিংক: $meeting_link\n";
            if($meeting_id) $sms_message .= "ID: $meeting_id\n";
            if($meeting_password) $sms_message .= "পাস: $meeting_password\n";
            $sms_message .= "\n- বাংলা LMS";
            
            $stmt = $pdo->prepare("INSERT INTO scheduled_sms (live_class_id, sender_id, recipient_type, course_id, message, scheduled_at) VALUES (?, ?, 'course_students', ?, ?, ?)");
            $stmt->execute([$class_id, $user_id, $course_id, $sms_message, $sms_scheduled_time]);
        }
        
        $message = '✅ লাইভ ক্লাস তৈরি হয়েছে!';
        $msg_type = 'success';
    }
}

// ==================== SEND MANUAL SMS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_sms'])) {
    $sms_message = trim($_POST['sms_message']);
    $sms_type = $_POST['sms_type'];
    $sms_course_id = $_POST['sms_course_id'] ?? null;
    $single_phone = trim($_POST['single_phone'] ?? '');
    
    if(empty($sms_message)) {
        $message = 'মেসেজ লিখুন';
        $msg_type = 'danger';
    } else {
        $sent = 0;
        if($sms_type == 'single' && !empty($single_phone) && isset($sms)) {
            if($sms->sendSMS($single_phone, $sms_message)) $sent = 1;
        } elseif($sms_type == 'course' && $sms_course_id) {
            $stmt = $pdo->prepare("SELECT u.phone FROM users u JOIN enrollments e ON u.id=e.user_id WHERE e.course_id=? AND e.payment_status='completed' AND u.phone IS NOT NULL");
            $stmt->execute([$sms_course_id]);
            $phones = $stmt->fetchAll();
            if(isset($sms)) foreach($phones as $p) { if($sms->sendSMS($p['phone'], $sms_message)) $sent++; }
        }
        $message = "✅ $sent জনকে SMS পাঠানো হয়েছে!";
        $msg_type = 'success';
    }
}

// ==================== GET DATA ====================
$msg = $_GET['msg'] ?? $message;
$msg_type = $_GET['type'] ?? $msg_type;

// Load config
$live_config = [];
if(file_exists('../includes/live_config.json')) {
    $live_config = json_decode(file_get_contents('../includes/live_config.json'), true) ?: [];
}

// Get courses
if($user_role == 'instructor') {
    $stmt = $pdo->prepare("SELECT id, title_bn FROM courses WHERE instructor_id=? AND status='published'");
    $stmt->execute([$user_id]);
} else {
    $stmt = $pdo->query("SELECT id, title_bn FROM courses WHERE status='published'");
}
$courses = $stmt->fetchAll();

// Get live classes
if($user_role == 'instructor') {
    $stmt = $pdo->prepare("SELECT lc.*, c.title_bn as course_name FROM live_classes lc LEFT JOIN courses c ON lc.course_id=c.id WHERE lc.instructor_id=? ORDER BY lc.scheduled_at DESC");
    $stmt->execute([$user_id]);
} else {
    $stmt = $pdo->query("SELECT lc.*, c.title_bn as course_name, u.full_name as instructor_name FROM live_classes lc LEFT JOIN courses c ON lc.course_id=c.id LEFT JOIN users u ON lc.instructor_id=u.id ORDER BY lc.scheduled_at DESC");
}
$live_classes = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>লাইভ ক্লাস - বাংলা LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #6C5CE7; --gradient: linear-gradient(135deg, #667eea, #764ba2); --shadow: 0 3px 15px rgba(0,0,0,0.08); }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { background:#f0f2f8; font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif; }
        .navbar { background:white; box-shadow:0 2px 10px rgba(0,0,0,0.06); padding:12px 0; position:sticky; top:0; z-index:100; }
        .navbar-brand { font-weight:700; color:var(--primary)!important; text-decoration:none; }
        .main-card { background:white; border-radius:15px; padding:25px; box-shadow:var(--shadow); margin-bottom:20px; }
        .form-control, .form-select, textarea { border-radius:10px; padding:10px 15px; border:2px solid #e0e0e0; width:100%; margin-bottom:10px; }
        .form-control:focus, .form-select:focus { border-color:var(--primary); outline:none; box-shadow:0 0 0 3px rgba(108,92,231,0.08); }
        .btn { border-radius:50px; padding:10px 25px; font-weight:600; cursor:pointer; transition:0.3s; border:none; }
        .btn-primary { background:var(--gradient); color:white; }
        .btn-primary:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(108,92,231,0.3); }
        .btn-outline { border:2px solid var(--primary); color:var(--primary); background:white; }
        .btn-danger { background:#ff4757; color:white; }
        .btn-success { background:#28a745; color:white; }
        .btn-sm { padding:6px 15px; font-size:0.8rem; }
        .rounded-pill { border-radius:50px!important; }
        .alert { border-radius:10px; padding:12px 18px; margin-bottom:15px; }
        .alert-success { background:#eaffea; color:#3a3; }
        .alert-danger { background:#ffeaea; color:#c33; }
        .badge { padding:5px 12px; border-radius:20px; font-size:0.75rem; font-weight:600; }
        .class-card { border:1px solid #eee; border-radius:12px; padding:18px; margin-bottom:12px; transition:0.3s; }
        .class-card:hover { box-shadow:var(--shadow); }
        .class-card.live { border-left:4px solid #28a745; background:#f0fff4; }
        .class-card.upcoming { border-left:4px solid #ffc107; }
        .nav-tabs { border-bottom:2px solid #e0e0e0; margin-bottom:20px; }
        .nav-tabs .nav-link { border:none; color:#666; font-weight:600; padding:10px 20px; border-radius:10px 10px 0 0; }
        .nav-tabs .nav-link.active { color:var(--primary); border-bottom:3px solid var(--primary); background:none; }
        label { font-weight:600; font-size:0.9rem; margin-bottom:5px; display:block; }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <a href="dashboard.php" class="navbar-brand"><i class="fas fa-graduation-cap me-2"></i><?= $user_role=='admin'?'অ্যাডমিন':'ইন্সট্রাক্টর' ?> প্যানেল</a>
            <div class="d-flex gap-2">
                <a href="../dashboard.php" class="btn btn-outline btn-sm rounded-pill">ড্যাশবোর্ড</a>
                <a href="../logout.php" class="btn btn-danger btn-sm rounded-pill">লগআউট</a>
            </div>
        </div>
    </div>
</nav>

<div class="container py-4">
    <h3 class="mb-4"><i class="fas fa-video text-primary me-2"></i>লাইভ ক্লাস ম্যানেজমেন্ট</h3>
    
    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_type ?>"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    
    <!-- Tabs -->
    <ul class="nav nav-tabs">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#create">➕ ক্লাস তৈরি</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#all">📋 সকল ক্লাস (<?= count($live_classes) ?>)</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#sms">📱 SMS পাঠান</a></li>
        <?php if($user_role == 'admin'): ?>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#config">⚙️ কনফিগারেশন</a></li>
        <?php endif; ?>
    </ul>
    
    <div class="tab-content">
        
        <!-- CREATE CLASS -->
        <div class="tab-pane fade show active" id="create">
            <div class="row">
                <div class="col-lg-7">
                    <div class="main-card">
                        <h5 class="mb-3">নতুন লাইভ ক্লাস তৈরি করুন</h5>
                        <form method="POST">
                            <input type="hidden" name="create_class" value="1">
                            <div class="row">
                                <div class="col-md-6"><label>ক্লাসের নাম (বাংলা) *</label><input type="text" name="title_bn" class="form-control" required></div>
                                <div class="col-md-6"><label>Class Name (English)</label><input type="text" name="title_en" class="form-control"></div>
                                <div class="col-md-4">
                                    <label>প্ল্যাটফর্ম</label>
                                    <select name="platform" class="form-select">
                                        <option value="gmeet" <?= ($live_config['default_platform']??'')=='gmeet'?'selected':'' ?>>🔵 Google Meet</option>
                                        <option value="zoom" <?= ($live_config['default_platform']??'')=='zoom'?'selected':'' ?>>🔷 Zoom</option>
                                        <option value="other">🔶 অন্যান্য</option>
                                    </select>
                                </div>
                                <div class="col-md-4"><label>কোর্স</label><select name="course_id" class="form-select"><option value="">সাধারণ</option><?php foreach($courses as $c): ?><option value="<?=$c['id']?>"><?=htmlspecialchars($c['title_bn'])?></option><?php endforeach; ?></select></div>
                                <div class="col-md-4"><label>সময়কাল (মিনিট)</label><input type="number" name="duration" class="form-control" value="60"></div>
                                <div class="col-12"><label>মিটিং লিংক *</label><input type="url" name="meeting_link" class="form-control" required placeholder="https://meet.google.com/xxx বা Zoom লিংক" value="<?= ($live_config['default_platform']??'')=='gmeet' ? ($live_config['gmeet_default_link']??'') : (($live_config['default_platform']??'')=='zoom' ? ($live_config['zoom_default_link']??'') : '') ?>"></div>
                                <div class="col-md-4"><label>মিটিং আইডি</label><input type="text" name="meeting_id" class="form-control"></div>
                                <div class="col-md-4"><label>পাসওয়ার্ড</label><input type="text" name="meeting_password" class="form-control"></div>
                                <div class="col-md-4"><label>ক্লাসের সময় *</label><input type="datetime-local" name="scheduled_at" class="form-control" required></div>
                                <div class="col-md-6"><label>SMS কত মিনিট আগে?</label><select name="send_sms_before" class="form-select"><option value="0">পাঠাবেন না</option><option value="15">১৫ মিনিট</option><option value="30" selected>৩০ মিনিট</option><option value="60">১ ঘন্টা</option><option value="1440">১ দিন</option></select></div>
                                <div class="col-12"><label>বিবরণ</label><textarea name="description" class="form-control" rows="2"></textarea></div>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 mt-3"><i class="fas fa-video me-1"></i> লাইভ ক্লাস তৈরি করুন</button>
                        </form>
                    </div>
                </div>
                <div class="col-lg-5">
                    <div class="main-card">
                        <h5 class="mb-3">ℹ️ গাইড</h5>
                        <div class="p-3 rounded-3 mb-2" style="background:#e8f0fe;"><strong>🔵 Google Meet:</strong><br><small>meet.google.com → New Meeting → Copy link</small></div>
                        <div class="p-3 rounded-3" style="background:#e8f5fe;"><strong>🔷 Zoom:</strong><br><small>zoom.us → Schedule → Copy link, ID, Password</small></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- ALL CLASSES -->
        <div class="tab-pane fade" id="all">
            <div class="main-card">
                <?php if(count($live_classes) > 0): ?>
                    <?php foreach($live_classes as $cls): 
                        $is_live = (strtotime($cls['scheduled_at']) <= time() && strtotime($cls['scheduled_at']) + ($cls['duration_minutes']*60) >= time());
                        $is_past = (strtotime($cls['scheduled_at']) + ($cls['duration_minutes']*60) < time());
                    ?>
                        <div class="class-card <?= $is_live?'live':($is_past?'':'upcoming') ?>">
                            <div class="d-flex justify-content-between flex-wrap">
                                <div>
                                    <span class="badge bg-<?= $cls['platform']=='gmeet'?'primary':'info' ?>"><?= $cls['platform']=='gmeet'?'🔵 GMeet':'🔷 Zoom' ?></span>
                                    <?php if($is_live): ?><span class="badge bg-danger">🔴 LIVE</span><?php endif; ?>
                                    <h6 class="mt-2"><?= htmlspecialchars($cls['title_bn']) ?></h6>
                                    <small>📅 <?= date('d M, h:i A', strtotime($cls['scheduled_at'])) ?> | ⏱️ <?= $cls['duration_minutes'] ?> min</small>
                                    <?php if($cls['course_name']): ?><br><small>📚 <?= htmlspecialchars($cls['course_name']) ?></small><?php endif; ?>
                                    <?php if(!$is_past): ?>
                                        <br><a href="<?= htmlspecialchars($cls['meeting_link']) ?>" target="_blank" class="btn btn-success btn-sm rounded-pill mt-2">▶️ জয়েন</a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-center text-muted py-4">কোন লাইভ ক্লাস নেই</p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- SMS -->
        <div class="tab-pane fade" id="sms">
            <div class="main-card">
                <h5 class="mb-3">📱 SMS পাঠান</h5>
                <form method="POST">
                    <input type="hidden" name="send_sms" value="1">
                    <div class="row">
                        <div class="col-md-4"><label>ধরণ</label><select name="sms_type" class="form-select" onchange="toggleSms(this.value)"><option value="single">একক নম্বর</option><option value="course">কোর্সের শিক্ষার্থী</option></select></div>
                        <div class="col-md-4" id="courseDiv" style="display:none;"><label>কোর্স</label><select name="sms_course_id" class="form-select"><?php foreach($courses as $c): ?><option value="<?=$c['id']?>"><?=htmlspecialchars($c['title_bn'])?></option><?php endforeach; ?></select></div>
                        <div class="col-md-4" id="phoneDiv"><label>ফোন</label><input type="text" name="single_phone" class="form-control" placeholder="01XXXXXXXXX"></div>
                    </div>
                    <label class="mt-2">মেসেজ</label>
                    <textarea name="sms_message" class="form-control" rows="3" required placeholder="মেসেজ লিখুন..."></textarea>
                    <button type="submit" class="btn btn-primary mt-2"><i class="fas fa-paper-plane me-1"></i> পাঠান</button>
                </form>
            </div>
        </div>
        
        <!-- CONFIG (Admin Only) -->
        <?php if($user_role == 'admin'): ?>
        <div class="tab-pane fade" id="config">
            <div class="main-card">
                <h5 class="mb-3"><i class="fas fa-cog me-2"></i>Zoom & Google Meet কনফিগারেশন</h5>
                <p class="text-muted small">এই সেটিংস শুধুমাত্র অ্যাডমিন দেখতে ও পরিবর্তন করতে পারবেন। ইন্সট্রাক্টররা ডিফল্ট লিংক ব্যবহার করতে পারবেন।</p>
                <form method="POST">
                    <input type="hidden" name="save_config" value="1">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-primary">🔵 Google Meet</h6>
                            <label>ডিফল্ট GMeet লিংক</label>
                            <input type="url" name="gmeet_default_link" class="form-control" value="<?= htmlspecialchars($live_config['gmeet_default_link'] ?? '') ?>" placeholder="https://meet.google.com/your-default-room">
                            <small class="text-muted">ইন্সট্রাক্টররা ক্লাস তৈরি করার সময় এটি অটো-ফিল হবে</small>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-info">🔷 Zoom</h6>
                            <label>ডিফল্ট Zoom লিংক</label>
                            <input type="url" name="zoom_default_link" class="form-control" value="<?= htmlspecialchars($live_config['zoom_default_link'] ?? '') ?>" placeholder="https://zoom.us/j/your-meeting-id">
                            <label class="mt-2">Zoom API Key</label>
                            <input type="text" name="zoom_api_key" class="form-control" value="<?= htmlspecialchars($live_config['zoom_api_key'] ?? '') ?>" placeholder="Zoom API Key">
                            <label class="mt-2">Zoom API Secret</label>
                            <input type="text" name="zoom_api_secret" class="form-control" value="<?= htmlspecialchars($live_config['zoom_api_secret'] ?? '') ?>" placeholder="Zoom API Secret">
                        </div>
                        <div class="col-md-6 mt-3">
                            <label>ডিফল্ট প্ল্যাটফর্ম</label>
                            <select name="default_platform" class="form-select">
                                <option value="gmeet" <?= ($live_config['default_platform']??'gmeet')=='gmeet'?'selected':'' ?>>🔵 Google Meet</option>
                                <option value="zoom" <?= ($live_config['default_platform']??'')=='zoom'?'selected':'' ?>>🔷 Zoom</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary mt-3"><i class="fas fa-save me-1"></i> কনফিগারেশন সংরক্ষণ</button>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSms(val) {
    document.getElementById('courseDiv').style.display = val==='course'?'block':'none';
    document.getElementById('phoneDiv').style.display = val==='single'?'block':'none';
}
</script>
</body>
</html>