<?php
// admin/instructors.php - Instructor Permission Management
session_start();
require_once '../includes/config.php';

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

$message = '';
$msg_type = 'info';

// ==================== ADD INSTRUCTOR ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_instructor'])) {
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone'] ?? '');
    $password = password_hash($_POST['password'] ?? '123456', PASSWORD_DEFAULT);
    $bio = trim($_POST['bio'] ?? '');
    
    if(empty($full_name) || empty($email)) {
        $message = 'নাম এবং ইমেইল প্রয়োজন';
        $msg_type = 'danger';
    } else {
        // Check email
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if($stmt->fetch()) {
            $message = 'ইমেইল ইতিমধ্যে ব্যবহৃত';
            $msg_type = 'danger';
        } else {
            $stmt = $pdo->prepare("INSERT INTO users (full_name, email, phone, password, role, bio) VALUES (?, ?, ?, ?, 'instructor', ?)");
            $stmt->execute([$full_name, $email, $phone, $password, $bio]);
            $instructor_id = $pdo->lastInsertId();
            
            // Add default permissions
            $stmt = $pdo->prepare("INSERT INTO instructor_permissions (instructor_id) VALUES (?)");
            $stmt->execute([$instructor_id]);
            
            $message = 'ইন্সট্রাক্টর যোগ হয়েছে!';
            $msg_type = 'success';
        }
    }
}

// ==================== UPDATE PERMISSIONS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_permissions'])) {
    $instructor_id = $_POST['instructor_id'];
    
    $permissions = [
        'can_create_course' => isset($_POST['can_create_course']) ? 1 : 0,
        'can_manage_lessons' => isset($_POST['can_manage_lessons']) ? 1 : 0,
        'can_create_quiz' => isset($_POST['can_create_quiz']) ? 1 : 0,
        'can_upload_files' => isset($_POST['can_upload_files']) ? 1 : 0,
        'can_create_live_class' => isset($_POST['can_create_live_class']) ? 1 : 0,
        'can_send_sms' => isset($_POST['can_send_sms']) ? 1 : 0,
        'can_view_students' => isset($_POST['can_view_students']) ? 1 : 0,
        'can_manage_enrollments' => isset($_POST['can_manage_enrollments']) ? 1 : 0,
        'can_view_revenue' => isset($_POST['can_view_revenue']) ? 1 : 0,
        'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];
    
    // Check if permissions exist
    $stmt = $pdo->prepare("SELECT id FROM instructor_permissions WHERE instructor_id = ?");
    $stmt->execute([$instructor_id]);
    
    if($stmt->fetch()) {
        // Update
        $sql = "UPDATE instructor_permissions SET ";
        $updates = [];
        $params = [];
        foreach($permissions as $key => $val) {
            $updates[] = "$key = ?";
            $params[] = $val;
        }
        $sql .= implode(', ', $updates) . " WHERE instructor_id = ?";
        $params[] = $instructor_id;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
    } else {
        // Insert
        $stmt = $pdo->prepare("INSERT INTO instructor_permissions (instructor_id, " . implode(',', array_keys($permissions)) . ") VALUES (?, " . implode(',', array_fill(0, count($permissions), '?')) . ")");
        $stmt->execute(array_merge([$instructor_id], array_values($permissions)));
    }
    
    $message = '✅ পারমিশন আপডেট হয়েছে!';
    $msg_type = 'success';
}

// ==================== DELETE INSTRUCTOR ====================
if(isset($_GET['delete']) && isset($_GET['id'])) {
    $id = $_GET['id'];
    $pdo->prepare("DELETE FROM instructor_permissions WHERE instructor_id = ?")->execute([$id]);
    $pdo->prepare("UPDATE courses SET instructor_id = NULL WHERE instructor_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'instructor'")->execute([$id]);
    
    header('Location: instructors.php?msg=ইন্সট্রাক্টর+ডিলিট+হয়েছে&type=success');
    exit;
}

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

// Get all instructors with permissions
$instructors = $pdo->query("
    SELECT u.*, 
           COALESCE(ip.can_create_course, 1) as can_create_course,
           COALESCE(ip.can_manage_lessons, 1) as can_manage_lessons,
           COALESCE(ip.can_create_quiz, 1) as can_create_quiz,
           COALESCE(ip.can_upload_files, 1) as can_upload_files,
           COALESCE(ip.can_create_live_class, 1) as can_create_live_class,
           COALESCE(ip.can_send_sms, 0) as can_send_sms,
           COALESCE(ip.can_view_students, 1) as can_view_students,
           COALESCE(ip.can_manage_enrollments, 0) as can_manage_enrollments,
           COALESCE(ip.can_view_revenue, 0) as can_view_revenue,
           COALESCE(ip.is_active, 1) as is_active,
           (SELECT COUNT(*) FROM courses WHERE instructor_id = u.id) as course_count,
           (SELECT COUNT(*) FROM enrollments e JOIN courses c ON e.course_id=c.id WHERE c.instructor_id=u.id AND e.payment_status='completed') as student_count
    FROM users u
    LEFT JOIN instructor_permissions ip ON u.id = ip.instructor_id
    WHERE u.role = 'instructor'
    ORDER BY u.created_at DESC
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ইন্সট্রাক্টর ম্যানেজমেন্ট - অ্যাডমিন</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; }
        
        .instructor-card {
            border:1px solid #eee; border-radius:15px; padding:20px;
            transition:all 0.3s ease; margin-bottom:15px; background:white;
        }
        .instructor-card:hover { box-shadow:var(--shadow); border-color:var(--primary); }
        .instructor-card.suspended { opacity:0.6; border-left:4px solid #dc3545; }
        
        .avatar-circle {
            width:50px; height:50px; border-radius:50%;
            display:flex; align-items:center; justify-content:center;
            color:white; font-weight:700; font-size:1.2rem;
        }
        
        .perm-badge {
            display:inline-block; padding:4px 10px; border-radius:20px;
            font-size:0.7rem; font-weight:600; margin:2px;
        }
        .perm-on { background:#d4f5e9; color:#11998e; }
        .perm-off { background:#f0f0f0; color:#999; text-decoration:line-through; }
        
        .form-check-input:checked { background-color:var(--primary); border-color:var(--primary); }
        
        .modal-header { background:var(--gradient); color:white; border-radius:15px 15px 0 0; }
        .modal-content { border-radius:15px; border:none; }
        
        .btn { border-radius:50px; padding:8px 20px; font-weight:600; transition:0.3s; }
        .btn-primary { background:var(--gradient); border:none; color:white; }
        .btn-primary:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(108,92,231,0.3); }
        .btn-sm { padding:5px 12px; font-size:0.8rem; }
        
        .stat-badge { padding:5px 12px; border-radius:20px; font-size:0.75rem; font-weight:600; }
        
        @media (max-width:768px) {
            .perm-badge { font-size:0.65rem; }
        }
    </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>অ্যাডমিন প্যানেল</a>
            <div class="d-flex gap-2">
                <a href="../dashboard.php" class="btn btn-outline-secondary btn-sm rounded-pill">ড্যাশবোর্ড</a>
                <a href="../logout.php" class="btn btn-sm rounded-pill" style="background:#ff4757;color:white;">লগআউট</a>
            </div>
        </div>
    </div>
</nav>

<div class="container py-4">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3><i class="fas fa-chalkboard-teacher text-primary me-2"></i>ইন্সট্রাক্টর ম্যানেজমেন্ট</h3>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addInstructorModal">
            <i class="fas fa-plus me-1"></i> নতুন ইন্সট্রাক্টর
        </button>
    </div>
    
    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_type ?> rounded-3"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    
    <!-- Instructors List -->
    <?php if(count($instructors) > 0): ?>
        <?php foreach($instructors as $ins): ?>
            <div class="instructor-card <?= !$ins['is_active']?'suspended':'' ?>">
                <div class="row align-items-center">
                    <div class="col-lg-3">
                        <div class="d-flex align-items-center gap-3">
                            <div class="avatar-circle" style="background:<?= !$ins['is_active']?'#dc3545':'var(--gradient)' ?>;">
                                <?= mb_substr($ins['full_name'], 0, 1) ?>
                            </div>
                            <div>
                                <strong><?= htmlspecialchars($ins['full_name']) ?></strong>
                                <br><small class="text-muted"><?= $ins['email'] ?></small>
                                <?php if(!$ins['is_active']): ?>
                                    <br><span class="badge bg-danger">⏸️ নিষ্ক্রিয়</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-5">
                        <div class="d-flex flex-wrap gap-1 mt-2 mt-lg-0">
                            <span class="perm-badge <?= $ins['can_create_course']?'perm-on':'perm-off' ?>">📚 কোর্স</span>
                            <span class="perm-badge <?= $ins['can_manage_lessons']?'perm-on':'perm-off' ?>">📹 লেসন</span>
                            <span class="perm-badge <?= $ins['can_create_quiz']?'perm-on':'perm-off' ?>">❓ কুইজ</span>
                            <span class="perm-badge <?= $ins['can_upload_files']?'perm-on':'perm-off' ?>">📁 ফাইল</span>
                            <span class="perm-badge <?= $ins['can_create_live_class']?'perm-on':'perm-off' ?>">🔴 লাইভ</span>
                            <span class="perm-badge <?= $ins['can_send_sms']?'perm-on':'perm-off' ?>">📱 SMS</span>
                            <span class="perm-badge <?= $ins['can_view_students']?'perm-on':'perm-off' ?>">👥 ছাত্র</span>
                            <span class="perm-badge <?= $ins['can_manage_enrollments']?'perm-on':'perm-off' ?>">📋 এনরোল</span>
                            <span class="perm-badge <?= $ins['can_view_revenue']?'perm-on':'perm-off' ?>">💰 আয়</span>
                        </div>
                    </div>
                    
                    <div class="col-lg-2">
                        <div class="d-flex gap-2 mt-2 mt-lg-0">
                            <span class="stat-badge bg-info text-white"><?= $ins['course_count'] ?> কোর্স</span>
                            <span class="stat-badge bg-success text-white"><?= $ins['student_count'] ?> ছাত্র</span>
                        </div>
                    </div>
                    
                    <div class="col-lg-2 text-end">
                        <button class="btn btn-outline-primary btn-sm" onclick="editPermissions(<?= htmlspecialchars(json_encode($ins)) ?>)">
                            <i class="fas fa-cog"></i> পারমিশন
                        </button>
                        <a href="?delete=1&id=<?= $ins['id'] ?>" class="btn btn-outline-danger btn-sm" 
                           onclick="return confirm('ডিলিট করবেন?')">
                            <i class="fas fa-trash"></i>
                        </a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="main-card text-center py-5">
            <i class="fas fa-users fa-3x text-muted mb-3" style="opacity:0.3;"></i>
            <p>কোন ইন্সট্রাক্টর নেই</p>
        </div>
    <?php endif; ?>
</div>

<!-- Add Instructor Modal -->
<div class="modal fade" id="addInstructorModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-user-plus me-2"></i>নতুন ইন্সট্রাক্টর</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="add_instructor" value="1">
                <div class="modal-body">
                    <div class="mb-2"><label>পূর্ণ নাম *</label><input type="text" name="full_name" class="form-control" required></div>
                    <div class="mb-2"><label>ইমেইল *</label><input type="email" name="email" class="form-control" required></div>
                    <div class="mb-2"><label>ফোন</label><input type="text" name="phone" class="form-control"></div>
                    <div class="mb-2"><label>পাসওয়ার্ড</label><input type="password" name="password" class="form-control" value="123456"></div>
                    <div class="mb-2"><label>বায়ো</label><textarea name="bio" class="form-control" rows="2"></textarea></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">বাতিল</button>
                    <button type="submit" class="btn btn-primary rounded-pill">যোগ করুন</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Permissions Modal -->
<div class="modal fade" id="permModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-cog me-2"></i>পারমিশন এডিট - <span id="permInstructorName"></span></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="update_permissions" value="1">
                <input type="hidden" name="instructor_id" id="permInstructorId">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-primary mb-3">📚 কন্টেন্ট পারমিশন</h6>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_create_course" id="p1"><label class="form-check-label" for="p1">কোর্স তৈরি করতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_manage_lessons" id="p2"><label class="form-check-label" for="p2">লেসন ম্যানেজ করতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_create_quiz" id="p3"><label class="form-check-label" for="p3">কুইজ তৈরি করতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_upload_files" id="p4"><label class="form-check-label" for="p4">ফাইল আপলোড করতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_create_live_class" id="p5"><label class="form-check-label" for="p5">লাইভ ক্লাস তৈরি করতে পারবে</label></div>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-warning mb-3">👥 অ্যাক্সেস পারমিশন</h6>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_send_sms" id="p6"><label class="form-check-label" for="p6">SMS পাঠাতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_view_students" id="p7"><label class="form-check-label" for="p7">শিক্ষার্থী দেখতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_manage_enrollments" id="p8"><label class="form-check-label" for="p8">এনরোলমেন্ট ম্যানেজ করতে পারবে</label></div>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="can_view_revenue" id="p9"><label class="form-check-label" for="p9">আয় দেখতে পারবে</label></div>
                            <hr>
                            <div class="form-check mb-2"><input class="form-check-input" type="checkbox" name="is_active" id="p10"><label class="form-check-label fw-bold" for="p10">✅ অ্যাকাউন্ট সক্রিয়</label></div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">বাতিল</button>
                    <button type="submit" class="btn btn-primary rounded-pill"><i class="fas fa-save me-1"></i> সংরক্ষণ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function editPermissions(data) {
    document.getElementById('permInstructorId').value = data.id;
    document.getElementById('permInstructorName').textContent = data.full_name;
    
    // Set checkboxes
    document.getElementById('p1').checked = data.can_create_course == 1;
    document.getElementById('p2').checked = data.can_manage_lessons == 1;
    document.getElementById('p3').checked = data.can_create_quiz == 1;
    document.getElementById('p4').checked = data.can_upload_files == 1;
    document.getElementById('p5').checked = data.can_create_live_class == 1;
    document.getElementById('p6').checked = data.can_send_sms == 1;
    document.getElementById('p7').checked = data.can_view_students == 1;
    document.getElementById('p8').checked = data.can_manage_enrollments == 1;
    document.getElementById('p9').checked = data.can_view_revenue == 1;
    document.getElementById('p10').checked = data.is_active == 1;
    
    new bootstrap.Modal(document.getElementById('permModal')).show();
}
</script>
</body>
</html>