<?php
// admin/learners.php - Manage Learners
session_start();
require_once '../includes/config.php';
require_once '../includes/sms_config.php';

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

$message = '';

// Suspend/Activate learner
if(isset($_GET['action']) && isset($_GET['id'])) {
    $user_id = $_GET['id'];
    
    if($_GET['action'] == 'suspend') {
        $stmt = $pdo->prepare("UPDATE users SET status = 'suspended' WHERE id = ? AND role = 'student'");
        $stmt->execute([$user_id]);
        $message = 'শিক্ষার্থী সাসপেন্ড করা হয়েছে';
    } elseif($_GET['action'] == 'activate') {
        $stmt = $pdo->prepare("UPDATE users SET status = 'active' WHERE id = ? AND role = 'student'");
        $stmt->execute([$user_id]);
        $message = 'শিক্ষার্থী পুনরায় সক্রিয় করা হয়েছে';
    } elseif($_GET['action'] == 'delete') {
        // Get user phone for SMS
        $stmt = $pdo->prepare("SELECT phone, full_name FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        // Send notification SMS
        if($user['phone'] && isset($sms)) {
            $sms->sendSMS($user['phone'], "দুঃখিত {$user['full_name']}, আপনার অ্যাকাউন্ট ডিলিট করা হয়েছে। - বাংলা LMS");
        }
        
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'student'");
        $stmt->execute([$user_id]);
        $message = 'শিক্ষার্থী ডিলিট করা হয়েছে';
    }
}

// Add new learner manually
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_learner'])) {
    $name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $password = password_hash($_POST['password'] ?? '123456', PASSWORD_DEFAULT);
    
    $stmt = $pdo->prepare("INSERT INTO users (full_name, email, phone, password, role, status) VALUES (?, ?, ?, ?, 'student', 'active')");
    $stmt->execute([$name, $email, $phone, $password]);
    
    // Send welcome SMS
    if(!empty($phone) && isset($sms)) {
        $sms->sendWelcomeSMS($phone, $name);
    }
    
    $message = 'নতুন শিক্ষার্থী যোগ করা হয়েছে!';
}

// Get learners
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? 'all';

$query = "SELECT * FROM users WHERE role = 'student'";
$params = [];

if($search) {
    $query .= " AND (full_name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $params = ["%$search%", "%$search%", "%$search%"];
}

if($status_filter == 'active') {
    $query .= " AND (status = 'active' OR status IS NULL)";
} elseif($status_filter == 'suspended') {
    $query .= " AND status = 'suspended'";
}

$query .= " ORDER BY created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$learners = $stmt->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; }
        body { background: #f5f6fa; font-family: 'Segoe UI', Arial, sans-serif; }
        .navbar { background: white; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 12px 0; }
        .main-card { background: white; border-radius: 15px; padding: 25px; box-shadow: 0 2px 15px rgba(0,0,0,0.08); }
        .btn-action { padding: 5px 10px; border-radius: 20px; font-size: 0.75rem; }
        .modal-header { background: var(--primary); color: white; border-radius: 15px 15px 0 0; }
        .search-box { border-radius: 25px; padding: 8px 20px; border: 2px solid #e0e0e0; }
    </style>
</head>
<body>
<nav class="navbar">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <a href="dashboard.php" class="text-decoration-none fw-bold text-primary">
                <i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন প্যানেল
            </a>
            <a href="../logout.php" class="btn btn-outline-danger btn-sm rounded-pill">লগআউট</a>
        </div>
    </div>
</nav>

<div class="container py-4">
    <div class="main-card">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h4><i class="fas fa-users text-primary me-2"></i>শিক্ষার্থী ম্যানেজমেন্ট</h4>
            <div>
                <button class="btn btn-primary rounded-pill me-2" data-bs-toggle="modal" data-bs-target="#addLearnerModal">
                    <i class="fas fa-plus me-1"></i> নতুন শিক্ষার্থী
                </button>
                <a href="dashboard.php" class="btn btn-outline-secondary rounded-pill">ড্যাশবোর্ড</a>
            </div>
        </div>
        
        <?php if($message): ?>
            <div class="alert alert-info rounded-pill"><?= $message ?></div>
        <?php endif; ?>
        
        <!-- Search & Filter -->
        <div class="row mb-4">
            <div class="col-md-6">
                <form method="GET" class="d-flex">
                    <input type="text" name="search" class="search-box flex-grow-1" placeholder="নাম, ইমেইল বা ফোন দিয়ে খুঁজুন..." value="<?= htmlspecialchars($search) ?>">
                    <button type="submit" class="btn btn-primary rounded-pill ms-2"><i class="fas fa-search"></i></button>
                </form>
            </div>
            <div class="col-md-6 text-end">
                <a href="?status=all" class="btn btn-sm <?= $status_filter=='all'?'btn-primary':'btn-outline-primary' ?> rounded-pill">সব</a>
                <a href="?status=active" class="btn btn-sm <?= $status_filter=='active'?'btn-success':'btn-outline-success' ?> rounded-pill">সক্রিয়</a>
                <a href="?status=suspended" class="btn btn-sm <?= $status_filter=='suspended'?'btn-warning':'btn-outline-warning' ?> rounded-pill">সাসপেন্ডেড</a>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>আইডি</th>
                        <th>নাম</th>
                        <th>ইমেইল</th>
                        <th>ফোন</th>
                        <th>স্ট্যাটাস</th>
                        <th>এনরোলমেন্ট</th>
                        <th>তারিখ</th>
                        <th>অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($learners as $learner): 
                        $enroll_count = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE user_id = ? AND payment_status = 'completed'");
                        $enroll_count->execute([$learner['id']]);
                        $count = $enroll_count->fetchColumn();
                    ?>
                        <tr>
                            <td>#<?= $learner['id'] ?></td>
                            <td><?= htmlspecialchars($learner['full_name']) ?></td>
                            <td><?= htmlspecialchars($learner['email']) ?></td>
                            <td><?= $learner['phone'] ?: 'N/A' ?></td>
                            <td>
                                <span class="badge bg-<?= ($learner['status'] ?? 'active') == 'suspended' ? 'warning' : 'success' ?> rounded-pill">
                                    <?= ($learner['status'] ?? 'active') == 'suspended' ? '⏸️ সাসপেন্ডেড' : '✅ সক্রিয়' ?>
                                </span>
                            </td>
                            <td><?= $count ?> টি কোর্স</td>
                            <td><?= date('d/m/Y', strtotime($learner['created_at'])) ?></td>
                            <td>
                                <?php if(($learner['status'] ?? 'active') != 'suspended'): ?>
                                    <a href="?action=suspend&id=<?= $learner['id'] ?>" class="btn btn-warning btn-action"
                                       onclick="return confirm('সাসপেন্ড করবেন?')">
                                        <i class="fas fa-pause"></i> সাসপেন্ড
                                    </a>
                                <?php else: ?>
                                    <a href="?action=activate&id=<?= $learner['id'] ?>" class="btn btn-success btn-action">
                                        <i class="fas fa-play"></i> সক্রিয়
                                    </a>
                                <?php endif; ?>
                                <a href="?action=delete&id=<?= $learner['id'] ?>" class="btn btn-danger btn-action"
                                   onclick="return confirm('ডিলিট করবেন?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <a href="learner-details.php?id=<?= $learner['id'] ?>" class="btn btn-info btn-action text-white">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Learner Modal -->
<div class="modal fade" id="addLearnerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 rounded-4">
            <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_learner" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">পূর্ণ নাম *</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ইমেইল *</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ফোন নম্বর</label>
                        <input type="text" name="phone" class="form-control" placeholder="01XXXXXXXXX">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">পাসওয়ার্ড</label>
                        <input type="password" name="password" class="form-control" value="123456">
                        <small class="text-muted">ডিফল্ট: 123456</small>
                    </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>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>