<?php
// enroll.php - Complete Enrollment System
ob_start();
require_once 'includes/config.php';
require_once 'includes/site-data.php';

// Check login
if(!isset($_SESSION['user_id'])) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    header('Location: auth.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$course_id = isset($_GET['course']) ? (int)$_GET['course'] : 0;
$package_id = isset($_GET['package']) ? (int)$_GET['package'] : 0;
$type = ''; $item = null; $price = 0; $item_name = '';

// Get course or package
if($course_id) {
    $stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ? AND status = 'published'");
    $stmt->execute([$course_id]);
    $item = $stmt->fetch();
    if($item) { $type = 'course'; $item_name = $item['title_bn']; $price = $item['price']; }
} elseif($package_id) {
    $stmt = $pdo->prepare("SELECT * FROM packages WHERE id = ?");
    $stmt->execute([$package_id]);
    $item = $stmt->fetch();
    if($item) { $type = 'package'; $item_name = $item['name_bn']; $price = $item['price']; }
}

if(!$item) { header('Location: courses.php'); exit; }

// Check duplicate
if($type == 'course') {
    $stmt = $pdo->prepare("SELECT id, payment_status FROM enrollments WHERE user_id = ? AND course_id = ?");
    $stmt->execute([$user_id, $course_id]);
    $existing = $stmt->fetch();
    if($existing) {
        if($existing['payment_status'] == 'completed') {
            $_SESSION['success'] = 'আপনি ইতিমধ্যে এনরোল করেছেন!';
        } else {
            $_SESSION['message'] = 'আপনার এনরোলমেন্ট প্রক্রিয়াধীন আছে।';
        }
        header('Location: course-details.php?id=' . $course_id);
        exit;
    }
}

// Handle enrollment
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $method = $_POST['payment_method'] ?? 'free';
    $trx = trim($_POST['transaction_id'] ?? '');
    
    // Determine status
    if($price == 0) {
        $status = 'completed'; // Free course - auto approve
    } elseif(!empty($trx)) {
        $status = 'completed'; // Has transaction ID - auto approve
    } else {
        $status = 'pending'; // No transaction ID - pending
    }
    
    $stmt = $pdo->prepare("INSERT INTO enrollments (user_id, course_id, package_id, amount_paid, payment_status, payment_method, transaction_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $type=='course'?$course_id:null, $type=='package'?$package_id:null, $price, $status, $method, $trx]);
    
    if($status == 'completed') {
        $_SESSION['success'] = 'এনরোলমেন্ট সফল! এখনই কোর্স শুরু করুন!';
    } else {
        $_SESSION['success'] = 'এনরোলমেন্ট জমা হয়েছে! অনুমোদনের পর কোর্স শুরু করতে পারবেন।';
    }
    
    header('Location: course-details.php?id=' . $course_id);
    exit;
}

$user = getUserData($pdo, $user_id);
$st = $S['site_title'] ?? 'স্বাস্থ্য কানন LMS';
$pc = $S['primary_color'] ?? '#2d6a4f';
$ph = $S['phone1'] ?? '';
?>
<!DOCTYPE html>
<html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>এনরোলমেন্ট - <?=htmlspecialchars($st)?></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:<?=$pc?>;--g1:linear-gradient(135deg,<?=$pc?>,#52b788)}
body{background:linear-gradient(135deg,#f5faf7,#e8f5e9);font-family:'Segoe UI',Arial,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;padding:20px}
.enroll-card{background:white;border-radius:24px;padding:40px 35px;max-width:500px;width:100%;box-shadow:0 20px 60px rgba(0,0,0,.12);text-align:center}
.icon-circle{width:80px;height:80px;border-radius:50%;background:var(--g1);display:inline-flex;align-items:center;justify-content:center;font-size:2rem;color:white;margin-bottom:20px}
.price{font-size:3rem;font-weight:800;color:var(--primary)}.price.free{color:#11998e}
.btn{font-weight:600;cursor:pointer;transition:.3s;border-radius:50px;padding:14px 30px;border:none;font-size:1rem;width:100%;text-decoration:none;display:inline-block}
.btn-primary{background:var(--g1);color:white}.btn-primary:hover{transform:translateY(-3px)}
.btn-success{background:#28a745;color:white}.btn-outline{background:white;border:2px solid #ddd;color:#555;margin-top:10px}
input,select{width:100%;padding:12px 15px;border-radius:12px;border:2px solid #e8eaef;margin-bottom:12px;font-size:.95rem;background:#fafbfd;text-align:left}
input:focus,select:focus{border-color:var(--primary);outline:none}
label{font-weight:600;font-size:.85rem;display:block;text-align:left;margin-bottom:4px;color:#444}
.alert{border-radius:12px;padding:14px 16px;margin-bottom:15px;font-size:.9rem;text-align:left}
.alert-info{background:#e8f0fe;color:#1967d2}.alert-success{background:#eaffea;color:#155724}
</style>
</head>
<body>
<div class="enroll-card">
    <div class="icon-circle"><i class="fas fa-shopping-cart"></i></div>
    <h3 style="color:#1a1a2e">এনরোলমেন্ট</h3>
    <p class="text-muted"><?=$type=='course'?'কোর্স':'প্যাকেজ'?>: <strong><?=htmlspecialchars($item_name)?></strong></p>
    <div class="price <?=$price==0?'free':''?>"><?=$price>0?'৳'.number_format($price):'বিনামূল্যে'?></div>
    
    <?php if($price == 0): ?>
        <div class="alert alert-info"><i class="fas fa-check-circle me-2"></i>ফ্রি কোর্স - সাথে সাথে এনরোল হবে</div>
        <form method="POST"><input type="hidden" name="payment_method" value="free">
            <button type="submit" class="btn btn-success"><i class="fas fa-check-circle me-2"></i> বিনামূল্যে এনরোল করুন</button>
        </form>
    <?php else: ?>
        <div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>ট্রানজেকশন আইডি দিলে সাথে সাথে এনরোল হবে। না দিলে অ্যাডমিন অনুমোদন সাপেক্ষে।</div>
        <form method="POST">
            <label>পেমেন্ট মেথড</label>
            <select name="payment_method" required><option value="">সিলেক্ট করুন</option><option value="bkash">বিকাশ</option><option value="nagad">নগদ</option><option value="rocket">রকেট</option></select>
            <label>ট্রানজেকশন আইডি (তাৎক্ষণিক এনরোলের জন্য)</label>
            <input type="text" name="transaction_id" placeholder="TRXID লিখুন">
            <small class="text-muted d-block mb-2">পেমেন্ট নম্বর: <strong><?=htmlspecialchars($ph)?: '01712-345678'?></strong></small>
            <button type="submit" class="btn btn-primary mt-3"><i class="fas fa-lock me-2"></i> এনরোল সম্পন্ন করুন</button>
        </form>
    <?php endif; ?>
    <a href="<?=$type=='course'?'course-details.php?id='.$course_id:'courses.php'?>" class="btn btn-outline"><i class="fas fa-arrow-left me-1"></i> ফিরে যান</a>
</div>
</body>
</html>
<?php ob_end_flush(); ?>