<?php
// admin/learner-details.php - Learner Details Page
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;
}

$learner_id = $_GET['id'] ?? 0;
$message = '';
$msg_type = 'info';

// Get learner info
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? AND role = 'student'");
$stmt->execute([$learner_id]);
$learner = $stmt->fetch();

if(!$learner) {
    header('Location: learners.php?msg=শিক্ষার্থী পাওয়া যায়নি&type=danger');
    exit;
}

// ==================== HANDLE ACTIONS ====================

// Send SMS
if(isset($_POST['send_sms'])) {
    $sms_message = trim($_POST['sms_message']);
    $phone = $learner['phone'];
    
    if(!empty($phone) && !empty($sms_message) && isset($sms)) {
        $result = $sms->sendSMS($phone, $sms_message);
        
        // Log SMS
        $stmt = $pdo->prepare("INSERT INTO sms_logs (user_id, phone, message, type, status) VALUES (?, ?, ?, 'notification', ?)");
        $stmt->execute([$learner_id, $phone, $sms_message, $result ? 'sent' : 'failed']);
        
        $message = $result ? '✅ SMS পাঠানো হয়েছে!' : '❌ SMS পাঠানো যায়নি';
        $msg_type = $result ? 'success' : 'danger';
    } else {
        $message = '❌ ফোন নম্বর বা মেসেজ নেই';
        $msg_type = 'danger';
    }
}

// Update notes
if(isset($_POST['update_notes'])) {
    $notes = trim($_POST['admin_notes']);
    $stmt = $pdo->prepare("UPDATE users SET admin_notes = ? WHERE id = ?");
    $stmt->execute([$notes, $learner_id]);
    $message = '✅ নোট আপডেট হয়েছে';
    $msg_type = 'success';
    
    // Refresh data
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$learner_id]);
    $learner = $stmt->fetch();
}

// Update status
if(isset($_GET['action']) && $_GET['action'] == 'suspend') {
    $stmt = $pdo->prepare("UPDATE users SET status = 'suspended' WHERE id = ?");
    $stmt->execute([$learner_id]);
    $message = '⏸️ শিক্ষার্থী সাসপেন্ড করা হয়েছে';
    $msg_type = 'warning';
    
    if($learner['phone'] && isset($sms)) {
        $sms->sendSMS($learner['phone'], "আপনার অ্যাকাউন্ট সাময়িকভাবে সাসপেন্ড করা হয়েছে। সাপোর্টে যোগাযোগ করুন। - বাংলা LMS");
    }
    
    $learner['status'] = 'suspended';
}

if(isset($_GET['action']) && $_GET['action'] == 'activate') {
    $stmt = $pdo->prepare("UPDATE users SET status = 'active' WHERE id = ?");
    $stmt->execute([$learner_id]);
    $message = '✅ শিক্ষার্থী পুনরায় সক্রিয় করা হয়েছে';
    $msg_type = 'success';
    
    if($learner['phone'] && isset($sms)) {
        $sms->sendSMS($learner['phone'], "আপনার অ্যাকাউন্ট পুনরায় সক্রিয় করা হয়েছে। - বাংলা LMS");
    }
    
    $learner['status'] = 'active';
}

// ==================== GET LEARNER DATA ====================

// Enrolled courses
$stmt = $pdo->prepare("
    SELECT e.*, c.title_bn, c.slug, c.id as course_id,
           e.enrolled_at, e.payment_status, e.amount_paid,
           e.expires_at
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
    WHERE e.user_id = ? AND e.payment_status = 'completed'
    ORDER BY e.enrolled_at DESC
");
$stmt->execute([$learner_id]);
$enrolled_courses = $stmt->fetchAll();

// Pending enrollments
$stmt = $pdo->prepare("
    SELECT e.*, c.title_bn, c.id as course_id
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
    WHERE e.user_id = ? AND e.payment_status = 'pending'
    ORDER BY e.enrolled_at DESC
");
$stmt->execute([$learner_id]);
$pending_courses = $stmt->fetchAll();

// Completed lessons
$stmt = $pdo->prepare("
    SELECT COUNT(*) as total
    FROM lesson_progress
    WHERE user_id = ? AND completed = 1
");
$stmt->execute([$learner_id]);
$completed_lessons = $stmt->fetchColumn();

// Quiz attempts
$stmt = $pdo->prepare("
    SELECT COUNT(*) as total, 
           SUM(CASE WHEN is_correct = 1 THEN 1 ELSE 0 END) as correct
    FROM quiz_attempts
    WHERE user_id = ?
");
$stmt->execute([$learner_id]);
$quiz_stats = $stmt->fetch();
$quiz_total = $quiz_stats['total'] ?? 0;
$quiz_correct = $quiz_stats['correct'] ?? 0;
$quiz_accuracy = $quiz_total > 0 ? round(($quiz_correct / $quiz_total) * 100) : 0;

// Total spent
$stmt = $pdo->prepare("
    SELECT COALESCE(SUM(amount_paid), 0) as total_spent
    FROM enrollments
    WHERE user_id = ? AND payment_status = 'completed'
");
$stmt->execute([$learner_id]);
$total_spent = $stmt->fetchColumn();

// SMS logs
$stmt = $pdo->prepare("
    SELECT * FROM sms_logs 
    WHERE user_id = ? 
    ORDER BY sent_at DESC 
    LIMIT 10
");
$stmt->execute([$learner_id]);
$sms_logs = $stmt->fetchAll();

// Recent activity (from lesson_progress)
$stmt = $pdo->prepare("
    SELECT lp.*, l.title_bn, c.title_bn as course_title
    FROM lesson_progress lp
    JOIN lessons l ON lp.lesson_id = l.id
    JOIN courses c ON l.course_id = c.id
    WHERE lp.user_id = ?
    ORDER BY lp.completed_at DESC
    LIMIT 10
");
$stmt->execute([$learner_id]);
$recent_activity = $stmt->fetchAll();

// Reviews given
$stmt = $pdo->prepare("
    SELECT r.*, c.title_bn
    FROM reviews r
    JOIN courses c ON r.course_id = c.id
    WHERE r.user_id = ?
    ORDER BY r.created_at DESC
");
$stmt->execute([$learner_id]);
$reviews = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষার্থী বিস্তারিত - <?= htmlspecialchars($learner['full_name']) ?></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); }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f5f6fa; font-family: 'Segoe UI', 'Hind Siliguri', Arial, sans-serif; }
        
        .navbar { background: white; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 12px 0; position: sticky; top: 0; z-index: 100; }
        
        .profile-header { background: var(--gradient); border-radius: 20px; padding: 30px; color: white; margin-bottom: 20px; }
        .profile-avatar { width: 80px; height: 80px; border-radius: 50%; background: rgba(255,255,255,0.3); display: flex; align-items: center; justify-content: center; font-size: 2rem; font-weight: bold; }
        
        .info-card { background: white; border-radius: 15px; padding: 20px; box-shadow: 0 3px 15px rgba(0,0,0,0.08); margin-bottom: 20px; }
        .info-card h5 { margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid #f0f0f0; }
        
        .stat-badge { display: inline-block; padding: 8px 16px; border-radius: 30px; font-weight: 600; font-size: 0.9rem; }
        
        .course-item { border: 1px solid #eee; border-radius: 10px; padding: 12px 15px; margin-bottom: 10px; transition: 0.2s; }
        .course-item:hover { border-color: var(--primary); background: #f8f9ff; }
        
        .activity-item { padding: 10px 0; border-bottom: 1px solid #f0f0f0; }
        .activity-item:last-child { border-bottom: none; }
        
        .btn-sm-round { border-radius: 50px; padding: 5px 15px; font-size: 0.8rem; }
        
        @media (max-width: 768px) {
            .profile-header { text-align: center; }
        }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <a href="dashboard.php" class="text-decoration-none fw-bold" style="color:var(--primary);">
                    <i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন প্যানেল
                </a>
            </div>
            <div>
                <a href="learners.php" class="btn btn-outline-secondary btn-sm-round me-2">
                    <i class="fas fa-arrow-left me-1"></i> শিক্ষার্থী তালিকা
                </a>
                <a href="../logout.php" class="btn btn-outline-danger btn-sm-round">লগআউট</a>
            </div>
        </div>
    </div>
</nav>

<div class="container py-4">
    
    <!-- Message -->
    <?php if($message): ?>
        <div class="alert alert-<?= $msg_type ?> alert-dismissible fade show rounded-pill">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <!-- Profile Header -->
    <div class="profile-header">
        <div class="row align-items-center">
            <div class="col-md-8">
                <div class="d-flex align-items-center gap-3">
                    <div class="profile-avatar">
                        <?= mb_substr($learner['full_name'], 0, 1) ?>
                    </div>
                    <div>
                        <h3 class="mb-1"><?= htmlspecialchars($learner['full_name']) ?></h3>
                        <p class="mb-1 opacity-75">
                            <i class="fas fa-envelope me-1"></i> <?= htmlspecialchars($learner['email']) ?>
                        </p>
                        <p class="mb-0 opacity-75">
                            <i class="fas fa-phone me-1"></i> <?= $learner['phone'] ?: 'N/A' ?>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                <span class="stat-badge bg-<?= ($learner['status'] ?? 'active') == 'suspended' ? 'warning' : 'success' ?> text-dark">
                    <?= ($learner['status'] ?? 'active') == 'suspended' ? '⏸️ সাসপেন্ডেড' : '✅ সক্রিয়' ?>
                </span>
                <br class="d-none d-md-block">
                <small class="opacity-75">রেজিস্টার্ড: <?= date('d M Y', strtotime($learner['created_at'])) ?></small>
            </div>
        </div>
    </div>
    
    <div class="row g-4">
        <!-- Left Column -->
        <div class="col-lg-8">
            <!-- Statistics -->
            <div class="row g-3 mb-3">
                <div class="col-6 col-md-3">
                    <div class="info-card text-center">
                        <h4 class="text-primary mb-0"><?= count($enrolled_courses) ?></h4>
                        <small class="text-muted">এনরোল্ড কোর্স</small>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="info-card text-center">
                        <h4 class="text-success mb-0"><?= $completed_lessons ?></h4>
                        <small class="text-muted">সম্পন্ন লেসন</small>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="info-card text-center">
                        <h4 class="text-warning mb-0"><?= $quiz_accuracy ?>%</h4>
                        <small class="text-muted">কুইজ নির্ভুলতা</small>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="info-card text-center">
                        <h4 class="text-danger mb-0">৳<?= number_format($total_spent) ?></h4>
                        <small class="text-muted">মোট খরচ</small>
                    </div>
                </div>
            </div>
            
            <!-- Enrolled Courses -->
            <div class="info-card">
                <h5><i class="fas fa-book text-primary me-2"></i>এনরোল্ড কোর্স (<?= count($enrolled_courses) ?>)</h5>
                <?php if(count($enrolled_courses) > 0): ?>
                    <?php foreach($enrolled_courses as $ec): ?>
                        <div class="course-item d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?= htmlspecialchars($ec['title_bn']) ?></strong>
                                <br>
                                <small class="text-muted">
                                    এনরোল্ড: <?= date('d M Y', strtotime($ec['enrolled_at'])) ?> | 
                                    মূল্য: ৳<?= number_format($ec['amount_paid']) ?>
                                </small>
                            </div>
                            <div class="d-flex gap-2">
                                <?php if($ec['expires_at']): ?>
                                    <small class="text-warning">মেয়াদ: <?= date('d/m/y', strtotime($ec['expires_at'])) ?></small>
                                <?php endif; ?>
                                <a href="../course-details.php?id=<?= $ec['course_id'] ?>" target="_blank" class="btn btn-sm btn-outline-primary btn-sm-round">
                                    <i class="fas fa-external-link-alt"></i>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted text-center">কোন কোর্স এনরোল করা নেই</p>
                <?php endif; ?>
            </div>
            
            <!-- Pending Enrollments -->
            <?php if(count($pending_courses) > 0): ?>
                <div class="info-card">
                    <h5><i class="fas fa-clock text-warning me-2"></i>পেন্ডিং এনরোলমেন্ট (<?= count($pending_courses) ?>)</h5>
                    <?php foreach($pending_courses as $pc): ?>
                        <div class="course-item d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?= htmlspecialchars($pc['title_bn']) ?></strong>
                                <br><small class="text-muted">তারিখ: <?= date('d M Y', strtotime($pc['enrolled_at'])) ?></small>
                            </div>
                            <a href="enrollments.php?approve=1&id=<?= $pc['id'] ?>" class="btn btn-success btn-sm-round">
                                অনুমোদন করুন
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <!-- Recent Activity -->
            <div class="info-card">
                <h5><i class="fas fa-history text-info me-2"></i>সাম্প্রতিক কার্যক্রম</h5>
                <?php if(count($recent_activity) > 0): ?>
                    <?php foreach($recent_activity as $activity): ?>
                        <div class="activity-item">
                            <div class="d-flex gap-2">
                                <i class="fas fa-check-circle text-success mt-1"></i>
                                <div>
                                    <strong><?= htmlspecialchars($activity['title_bn'] ?? 'লেসন') ?></strong>
                                    <br>
                                    <small class="text-muted">
                                        <?= htmlspecialchars($activity['course_title']) ?> | 
                                        <?= $activity['completed_at'] ? date('d M Y H:i', strtotime($activity['completed_at'])) : 'N/A' ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted text-center">কোন কার্যক্রম নেই</p>
                <?php endif; ?>
            </div>
            
            <!-- Reviews -->
            <?php if(count($reviews) > 0): ?>
                <div class="info-card">
                    <h5><i class="fas fa-star text-warning me-2"></i>দেওয়া রিভিউ</h5>
                    <?php foreach($reviews as $review): ?>
                        <div class="activity-item">
                            <strong><?= htmlspecialchars($review['title_bn']) ?></strong>
                            <div class="text-warning small">
                                <?php for($i=1; $i<=5; $i++): ?>
                                    <i class="fas fa-star <?= $i <= $review['rating'] ? '' : 'text-muted' ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <p class="mb-0 small"><?= htmlspecialchars($review['comment']) ?></p>
                            <small class="text-muted"><?= date('d M Y', strtotime($review['created_at'])) ?></small>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Right Column -->
        <div class="col-lg-4">
            <!-- Actions -->
            <div class="info-card">
                <h5><i class="fas fa-cog text-primary me-2"></i>অ্যাকশন</h5>
                
                <div class="d-grid gap-2">
                    <?php if(($learner['status'] ?? 'active') != 'suspended'): ?>
                        <a href="?action=suspend&id=<?= $learner_id ?>" class="btn btn-warning btn-sm-round"
                           onclick="return confirm('সাসপেন্ড করবেন?')">
                            <i class="fas fa-pause me-1"></i> সাসপেন্ড করুন
                        </a>
                    <?php else: ?>
                        <a href="?action=activate&id=<?= $learner_id ?>" class="btn btn-success btn-sm-round">
                            <i class="fas fa-play me-1"></i> পুনরায় সক্রিয় করুন
                        </a>
                    <?php endif; ?>
                    
                    <button class="btn btn-info btn-sm-round text-white" data-bs-toggle="modal" data-bs-target="#smsModal">
                        <i class="fas fa-sms me-1"></i> SMS পাঠান
                    </button>
                    
                    <a href="learners.php?action=delete&id=<?= $learner_id ?>" class="btn btn-danger btn-sm-round"
                       onclick="return confirm('⚠️ সত্যিই ডিলিট করবেন?')">
                        <i class="fas fa-trash me-1"></i> ডিলিট করুন
                    </a>
                </div>
            </div>
            
            <!-- Notes -->
            <div class="info-card">
                <h5><i class="fas fa-sticky-note text-warning me-2"></i>অ্যাডমিন নোট</h5>
                <form method="POST">
                    <input type="hidden" name="update_notes" value="1">
                    <textarea name="admin_notes" class="form-control mb-2" rows="3" 
                              placeholder="শিক্ষার্থী সম্পর্কে নোট..."><?= htmlspecialchars($learner['admin_notes'] ?? '') ?></textarea>
                    <button type="submit" class="btn btn-primary btn-sm-round w-100">নোট সংরক্ষণ</button>
                </form>
            </div>
            
            <!-- SMS Logs -->
            <div class="info-card">
                <h5><i class="fas fa-envelope text-info me-2"></i>SMS লগ (সর্বশেষ ১০)</h5>
                <?php if(count($sms_logs) > 0): ?>
                    <?php foreach($sms_logs as $log): ?>
                        <div class="activity-item">
                            <small class="text-muted"><?= date('d/m/y H:i', strtotime($log['sent_at'])) ?></small>
                            <br>
                            <small><?= mb_substr(htmlspecialchars($log['message']), 0, 50) ?>...</small>
                            <br>
                            <span class="badge bg-<?= $log['status'] == 'sent' ? 'success' : 'danger' ?>">
                                <?= $log['status'] ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted text-center small">কোন SMS লগ নেই</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- SMS Modal -->
<div class="modal fade" id="smsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 rounded-4">
            <div class="modal-header" style="background:var(--gradient);color:white;border-radius:15px 15px 0 0;">
                <h5 class="modal-title"><i class="fas fa-sms me-2"></i>SMS পাঠান</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="send_sms" value="1">
                <div class="modal-body">
                    <p>প্রাপক: <strong><?= htmlspecialchars($learner['full_name']) ?></strong> (<?= $learner['phone'] ?: 'ফোন নম্বর নেই' ?>)</p>
                    <div class="mb-2">
                        <label class="form-label">মেসেজ</label>
                        <textarea name="sms_message" class="form-control" rows="4" required 
                                  placeholder="মেসেজ লিখুন..." maxlength="480"></textarea>
                        <small class="text-muted">সর্বোচ্চ ৪৮০ অক্ষর (৩টি SMS)</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">
                        <i class="fas fa-paper-plane 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>
</body>
</html>