<?php
// admin/approvals.php - Enrollment Approval Management
session_start();
require_once '../includes/config.php';
require_once '../includes/sms_config.php';
require_once '../includes/email_helper.php';

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

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

// ==================== APPROVE ENROLLMENT ====================
if(isset($_GET['approve']) && isset($_GET['id'])) {
    $enrollment_id = (int)$_GET['id'];
    
    $stmt = $pdo->prepare("
        SELECT e.*, u.full_name, u.email, u.phone, c.title_bn, c.id as course_id
        FROM enrollments e
        JOIN users u ON e.user_id = u.id
        JOIN courses c ON e.course_id = c.id
        WHERE e.id = ?
    ");
    $stmt->execute([$enrollment_id]);
    $enr = $stmt->fetch();
    
    if($enr) {
        // Approve
        $pdo->prepare("UPDATE enrollments SET payment_status='completed', approved_by=?, approved_at=NOW(), admin_notes=CONCAT(IFNULL(admin_notes,''), '\nApproved by admin on '.NOW()) WHERE id=?")->execute([$admin_id, $enrollment_id]);
        
        // Send SMS
        if(isset($sms) && !empty($enr['phone'])) {
            $sms->sendApprovalSMS($enr['phone'], $enr['title_bn'], $enrollment_id);
        }
        
        // Send Email
        if(!empty($enr['email'])) {
            sendApprovalEmail($enr['email'], $enr['full_name'], $enr['title_bn'], $enrollment_id);
        }
        
        $message = "✅ এনরোলমেন্ট #{$enrollment_id} অনুমোদিত হয়েছে! SMS ও ইমেইল পাঠানো হয়েছে।";
        $msg_type = 'success';
    }
    header('Location: approvals.php?msg='.urlencode($message).'&type='.$msg_type);
    exit;
}

// ==================== REJECT ENROLLMENT ====================
if(isset($_GET['reject']) && isset($_GET['id'])) {
    $enrollment_id = (int)$_GET['id'];
    $reason = $_GET['reason'] ?? 'পেমেন্ট যাচাই করা যায়নি';
    
    $stmt = $pdo->prepare("
        SELECT e.*, u.full_name, u.email, u.phone, c.title_bn
        FROM enrollments e
        JOIN users u ON e.user_id = u.id
        JOIN courses c ON e.course_id = c.id
        WHERE e.id = ?
    ");
    $stmt->execute([$enrollment_id]);
    $enr = $stmt->fetch();
    
    if($enr) {
        // Reject
        $pdo->prepare("UPDATE enrollments SET payment_status='rejected', admin_notes=?, rejected_reason=? WHERE id=?")->execute(["Rejected: $reason", $reason, $enrollment_id]);
        
        // Send SMS
        if(isset($sms) && !empty($enr['phone'])) {
            $sms->sendRejectionSMS($enr['phone'], $enr['title_bn'], $reason);
        }
        
        // Send Email
        if(!empty($enr['email'])) {
            sendRejectionEmail($enr['email'], $enr['full_name'], $enr['title_bn'], $reason);
        }
        
        $message = "❌ এনরোলমেন্ট #{$enrollment_id} রিজেক্ট করা হয়েছে। SMS ও ইমেইল পাঠানো হয়েছে।";
        $msg_type = 'warning';
    }
    header('Location: approvals.php?msg='.urlencode($message).'&type='.$msg_type);
    exit;
}

// ==================== DELETE ENROLLMENT ====================
if(isset($_GET['delete']) && isset($_GET['id'])) {
    $enrollment_id = (int)$_GET['id'];
    $pdo->prepare("DELETE FROM enrollments WHERE id = ?")->execute([$enrollment_id]);
    $message = "🗑️ এনরোলমেন্ট #{$enrollment_id} ডিলিট করা হয়েছে।";
    $msg_type = 'info';
    header('Location: approvals.php?msg='.urlencode($message).'&type='.$msg_type);
    exit;
}

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

// Get pending enrollments
$stmt = $pdo->query("
    SELECT e.*, u.full_name, u.email, u.phone, c.title_bn as course_name, c.price as course_price
    FROM enrollments e
    JOIN users u ON e.user_id = u.id
    JOIN courses c ON e.course_id = c.id
    WHERE e.payment_status = 'pending'
    ORDER BY e.enrolled_at DESC
");
$pending = $stmt->fetchAll();

// Get recent approvals
$stmt = $pdo->query("
    SELECT e.*, u.full_name, c.title_bn as course_name
    FROM enrollments e
    JOIN users u ON e.user_id = u.id
    JOIN courses c ON e.course_id = c.id
    WHERE e.payment_status IN ('completed','rejected')
    ORDER BY e.enrolled_at DESC LIMIT 20
");
$recent = $stmt->fetchAll();

$pending_count = count($pending);
?>
<!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,.06)}
body{background:#f0f2f8;font-family:'Segoe UI',Arial,sans-serif}
.navbar{background:white;padding:12px 0;box-shadow:0 2px 10px rgba(0,0,0,.06);position:sticky;top:0;z-index:100}
.container{max-width:1100px;margin:0 auto;padding:20px}
.page-header{background:var(--gradient);color:white;border-radius:16px;padding:25px;margin-bottom:20px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px}
.main-card{background:white;border-radius:16px;padding:22px;box-shadow:var(--shadow);margin-bottom:20px}
.enr-row{display:flex;justify-content:space-between;align-items:center;padding:15px;border:1px solid #eee;border-radius:12px;margin-bottom:8px;transition:.3s;flex-wrap:wrap;gap:10px}
.enr-row:hover{box-shadow:var(--shadow);border-color:var(--primary)}
.enr-row.pending{border-left:4px solid #ffc107;background:#fffef5}
.enr-row.approved{border-left:4px solid #28a745;background:#f0fff4}
.enr-row.rejected{border-left:4px solid #dc3545;background:#fff5f5}
.badge-status{padding:4px 12px;border-radius:20px;font-size:.75rem;font-weight:600}
.btn{border-radius:50px;padding:8px 18px;font-weight:600;cursor:pointer;border:none;transition:.3s;text-decoration:none;display:inline-flex;align-items:center;gap:5px;font-size:.85rem}
.btn-success{background:#28a745;color:white}.btn-danger{background:#dc3545;color:white}.btn-info{background:#17a2b8;color:white}.btn-warning{background:#ffc107;color:#333}
.btn-sm{padding:5px 12px;font-size:.78rem}.alert{border-radius:10px;padding:12px 16px}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:20px}
.stat-card{background:white;border-radius:14px;padding:20px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.03)}
.stat-card h3{font-weight:800;margin:0}.stat-card p{color:#888;font-size:.8rem;margin:5px 0 0}
</style>
</head>
<body>
<nav class="navbar"><div class="container" style="display:flex;justify-content:space-between;align-items:center">
    <a href="dashboard.php" style="font-weight:700;color:var(--primary);text-decoration:none;font-size:1.1rem"><i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন</a>
    <a href="../logout.php" class="btn btn-sm" style="background:#ff4757;color:white">লগআউট</a>
</div></nav>

<div class="container">
    <div class="page-header"><h4><i class="fas fa-clipboard-check me-2"></i>এনরোলমেন্ট অনুমোদন</h4><span class="badge bg-warning text-dark" style="font-size:1rem;padding:8px 20px"><?=$pending_count?> টি পেন্ডিং</span></div>
    <?php if($msg):?><div class="alert alert-<?=$msg_type?>"><?=htmlspecialchars($msg)?></div><?php endif;?>
    
    <!-- Stats -->
    <div class="stats">
        <div class="stat-card"><h3 style="color:#ffc107"><?=$pending_count?></h3><p>⏳ পেন্ডিং</p></div>
        <div class="stat-card"><h3 style="color:#28a745"><?=count(array_filter($recent,function($r){return $r['payment_status']=='completed';}))?></h3><p>✅ অনুমোদিত</p></div>
        <div class="stat-card"><h3 style="color:#dc3545"><?=count(array_filter($recent,function($r){return $r['payment_status']=='rejected';}))?></h3><p>❌ রিজেক্টেড</p></div>
    </div>
    
    <!-- Pending Enrollments -->
    <div class="main-card"><h5 class="mb-3">⏳ পেন্ডিং এনরোলমেন্ট</h5>
        <?php if(count($pending)>0):?>
            <?php foreach($pending as $p):?>
            <div class="enr-row pending">
                <div><strong><?=htmlspecialchars($p['full_name'])?></strong><br><small><?=htmlspecialchars($p['course_name'])?> | ৳<?=number_format($p['amount_paid'])?> | <?=date('d/m/y',strtotime($p['enrolled_at']))?></small><br><small>📧 <?=$p['email']?> | 📞 <?=$p['phone']?></small></div>
                <div class="d-flex gap-2">
                    <a href="?approve=1&id=<?=$p['id']?>" class="btn btn-success btn-sm" onclick="return confirm('অনুমোদন করবেন? SMS ও ইমেইল পাঠানো হবে।')"><i class="fas fa-check"></i> অনুমোদন</a>
                    <button class="btn btn-danger btn-sm" onclick="rejectEnrollment(<?=$p['id']?>)"><i class="fas fa-times"></i> রিজেক্ট</button>
                    <a href="?delete=1&id=<?=$p['id']?>" class="btn btn-sm" style="background:#6c757d;color:white" onclick="return confirm('ডিলিট করবেন?')"><i class="fas fa-trash"></i></a>
                </div>
            </div>
            <?php endforeach;?>
        <?php else:?><p class="text-muted text-center py-3">কোন পেন্ডিং এনরোলমেন্ট নেই</p><?php endif;?>
    </div>
    
    <!-- Recent -->
    <div class="main-card"><h5 class="mb-3">📋 সাম্প্রতিক এনরোলমেন্ট</h5>
        <?php foreach($recent as $r):?>
        <div class="enr-row <?=$r['payment_status']=='completed'?'approved':'rejected'?>">
            <div><strong><?=htmlspecialchars($r['full_name'])?></strong> - <?=htmlspecialchars($r['course_name'])?><br><small><?=date('d/m/y H:i',strtotime($r['enrolled_at']))?></small></div>
            <span class="badge-status bg-<?=$r['payment_status']=='completed'?'success':'danger'?>"><?=$r['payment_status']=='completed'?'✅ অনুমোদিত':'❌ রিজেক্টেড'?></span>
        </div>
        <?php endforeach;?>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content border-0 rounded-4">
    <div class="modal-header" style="background:#dc3545;color:white;border-radius:15px 15px 0 0"><h6>❌ রিজেক্ট করার কারণ</h6><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
    <form method="GET" action="">
        <input type="hidden" name="reject" value="1"><input type="hidden" name="id" id="rejectId">
        <div class="modal-body">
            <label>কারণ লিখুন</label>
            <select name="reason" class="form-select mb-2">
                <option>পেমেন্ট যাচাই করা যায়নি</option><option>ভুল তথ্য প্রদান করা হয়েছে</option><option>ডুপ্লিকেট এনরোলমেন্ট</option><option>অন্যান্য</option>
            </select>
            <textarea name="reason_other" class="form-control" rows="2" placeholder="অথবা অন্য কারণ লিখুন..."></textarea>
        </div>
        <div class="modal-footer"><button class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">বাতিল</button><button type="submit" class="btn btn-danger 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>
<script>
function rejectEnrollment(id){document.getElementById('rejectId').value=id;new bootstrap.Modal(document.getElementById('rejectModal')).show();}
</script>
</body>
</html>