<?php
// admin/enrollments.php - Manage Enrollments
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;
}

// Handle approval
if(isset($_GET['approve']) && isset($_GET['id'])) {
    $enrollment_id = $_GET['id'];
    
    // Get enrollment details
    $stmt = $pdo->prepare("
        SELECT e.*, u.full_name, u.phone, u.email,
               COALESCE(c.title_bn, p.name_bn) as item_name
        FROM enrollments e
        JOIN users u ON e.user_id = u.id
        LEFT JOIN courses c ON e.course_id = c.id
        LEFT JOIN packages p ON e.package_id = p.id
        WHERE e.id = ?
    ");
    $stmt->execute([$enrollment_id]);
    $enrollment = $stmt->fetch();
    
    if($enrollment) {
        // Update status
        $stmt = $pdo->prepare("UPDATE enrollments SET payment_status = 'completed' WHERE id = ?");
        $stmt->execute([$enrollment_id]);
        
        // Send SMS confirmation
        if(!empty($enrollment['phone']) && isset($sms)) {
            $message = "অভিনন্দন {$enrollment['full_name']}!\n";
            $message .= "আপনার এনরোলমেন্ট অনুমোদিত হয়েছে।\n";
            $message .= "কোর্স: {$enrollment['item_name']}\n";
            $message .= "আইডি: #{$enrollment_id}\n";
            $message .= "- বাংলা LMS";
            
            $sms->sendSMS($enrollment['phone'], $message);
            
            // Log SMS
            $stmt = $pdo->prepare("INSERT INTO sms_logs (user_id, phone, message, type, status) VALUES (?, ?, ?, 'purchase', 'sent')");
            $stmt->execute([$enrollment['user_id'], $enrollment['phone'], $message]);
        }
        
        $_SESSION['success'] = "এনরোলমেন্ট #{$enrollment_id} অনুমোদিত হয়েছে এবং SMS পাঠানো হয়েছে!";
    }
    
    header('Location: enrollments.php');
    exit;
}

// Handle rejection
if(isset($_GET['reject']) && isset($_GET['id'])) {
    $stmt = $pdo->prepare("UPDATE enrollments SET payment_status = 'failed' WHERE id = ?");
    $stmt->execute([$_GET['id']]);
    $_SESSION['error'] = "এনরোলমেন্ট বাতিল করা হয়েছে।";
    header('Location: enrollments.php');
    exit;
}

// Get all enrollments
$status_filter = $_GET['status'] ?? 'all';
$query = "
    SELECT e.*, u.full_name, u.phone, u.email,
           COALESCE(c.title_bn, p.name_bn) as item_name,
           CASE WHEN e.course_id IS NOT NULL THEN 'course' ELSE 'package' END as item_type
    FROM enrollments e
    JOIN users u ON e.user_id = u.id
    LEFT JOIN courses c ON e.course_id = c.id
    LEFT JOIN packages p ON e.package_id = p.id
";
if($status_filter != 'all') {
    $query .= " WHERE e.payment_status = ?";
}
$query .= " ORDER BY e.enrolled_at DESC";

$stmt = $pdo->prepare($query);
if($status_filter != 'all') {
    $stmt->execute([$status_filter]);
} else {
    $stmt->execute();
}
$enrollments = $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); }
        .status-badge { padding: 5px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-completed { background: #d4edda; color: #155724; }
        .status-failed { background: #f8d7da; color: #721c24; }
        .btn-sm { padding: 5px 12px; border-radius: 20px; font-size: 0.8rem; }
        .table { font-size: 0.9rem; }
        .filter-btn { border-radius: 20px; padding: 6px 18px; font-size: 0.85rem; }
    </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-user-graduate text-primary me-2"></i>এনরোলমেন্ট ম্যানেজমেন্ট</h4>
            <a href="dashboard.php" class="btn btn-outline-secondary rounded-pill btn-sm">
                <i class="fas fa-arrow-left me-1"></i> ড্যাশবোর্ড
            </a>
        </div>
        
        <!-- Messages -->
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert alert-success rounded-pill">✅ <?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
        <?php endif; ?>
        <?php if(isset($_SESSION['error'])): ?>
            <div class="alert alert-danger rounded-pill">❌ <?= $_SESSION['error']; unset($_SESSION['error']); ?></div>
        <?php endif; ?>
        
        <!-- Filter Buttons -->
        <div class="d-flex gap-2 mb-4">
            <a href="?status=all" class="filter-btn btn <?= $status_filter == 'all' ? 'btn-primary' : 'btn-outline-primary' ?>">সব</a>
            <a href="?status=pending" class="filter-btn btn <?= $status_filter == 'pending' ? 'btn-warning' : 'btn-outline-warning' ?>">পেন্ডিং</a>
            <a href="?status=completed" class="filter-btn btn <?= $status_filter == 'completed' ? 'btn-success' : 'btn-outline-success' ?>">অনুমোদিত</a>
            <a href="?status=failed" class="filter-btn btn <?= $status_filter == 'failed' ? 'btn-danger' : 'btn-outline-danger' ?>">বাতিল</a>
        </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>
                        <th>অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($enrollments as $e): ?>
                        <tr>
                            <td>#<?= $e['id'] ?></td>
                            <td><?= htmlspecialchars($e['full_name']) ?><br><small class="text-muted"><?= $e['email'] ?></small></td>
                            <td><?= $e['phone'] ?: 'N/A' ?></td>
                            <td><?= htmlspecialchars($e['item_name'] ?: 'N/A') ?></td>
                            <td><span class="badge bg-info"><?= $e['item_type'] ?></span></td>
                            <td>৳<?= number_format($e['amount_paid'] ?: 0) ?></td>
                            <td><?= date('d/m/Y', strtotime($e['enrolled_at'])) ?></td>
                            <td>
                                <span class="status-badge status-<?= $e['payment_status'] ?>">
                                    <?= $e['payment_status'] == 'pending' ? '⏳ পেন্ডিং' : 
                                       ($e['payment_status'] == 'completed' ? '✅ অনুমোদিত' : '❌ বাতিল') ?>
                                </span>
                            </td>
                            <td>
                                <?php if($e['payment_status'] == 'pending'): ?>
                                    <a href="?approve=1&id=<?= $e['id'] ?>" class="btn btn-success btn-sm" 
                                       onclick="return confirm('অনুমোদন করবেন? SMS পাঠানো হবে।')">
                                        <i class="fas fa-check"></i> অনুমোদন
                                    </a>
                                    <a href="?reject=1&id=<?= $e['id'] ?>" class="btn btn-danger btn-sm"
                                       onclick="return confirm('বাতিল করবেন?')">
                                        <i class="fas fa-times"></i>
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    
                    <?php if(count($enrollments) == 0): ?>
                        <tr><td colspan="9" class="text-center py-4 text-muted">কোন এনরোলমেন্ট পাওয়া যায়নি</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>