<?php
// payment.php - Dynamic Payment Page
ob_start();
require_once 'includes/config.php';
require_once 'includes/site-data.php';
require_once 'includes/sms_config.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 enrollment
if($type == 'course') {
    $stmt = $pdo->prepare("SELECT id FROM enrollments WHERE user_id=? AND course_id=? AND payment_status IN ('completed','pending')");
    $stmt->execute([$user_id, $course_id]);
    if($stmt->fetch()) {
        $_SESSION['success'] = 'আপনি ইতিমধ্যে এনরোল করেছেন!';
        header('Location: course-details.php?id='.$course_id); exit;
    }
}

// Handle payment
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $method = $_POST['payment_method'] ?? 'bkash';
    $trxid = trim($_POST['transaction_id'] ?? '');
    $phone = trim($_POST['sender_phone'] ?? '');
    
    // Auto-complete enrollment
    $stmt = $pdo->prepare("INSERT INTO enrollments (user_id, course_id, package_id, amount_paid, payment_status, payment_method, transaction_id, notes) VALUES (?,?,?,?, 'completed', ?,?,?)");
    $stmt->execute([$user_id, $type=='course'?$course_id:null, $type=='package'?$package_id:null, $price, $method, $trxid, "Sender: $phone"]);
    
    // Package courses
    if($type == 'package') {
        $pc = $pdo->prepare("SELECT course_id FROM package_courses WHERE package_id=?");
        $pc->execute([$package_id]);
        while($c = $pc->fetch()) {
            $pdo->prepare("INSERT IGNORE INTO enrollments (user_id, course_id, amount_paid, payment_status) VALUES (?,?,0,'completed')")->execute([$user_id, $c['course_id']]);
        }
    }
    
    // SMS
    $u = $pdo->prepare("SELECT phone,full_name FROM users WHERE id=?"); $u->execute([$user_id]); $user_data = $u->fetch();
    if(isset($sms) && $user_data['phone']) {
        $sms->sendPurchaseConfirmation($user_data['phone'], ['name'=>$item_name, 'amount'=>$price]);
    }
    
    $_SESSION['success'] = '🎉 এনরোলমেন্ট সফল! এখনই শুরু করুন!';
    header('Location: '.($type=='course'?'course-details.php?id='.$course_id:'dashboard.php')); exit;
}

$user = getUserData($pdo, $user_id);

// Dynamic settings
$site_title = $S['site_title'] ?? 'বাংলা LMS';
$logo_text = $S['logo_text'] ?? 'বাংলা LMS';
$logo_icon = $S['logo_icon'] ?? 'fa-graduation-cap';
$primary_color = $S['primary_color'] ?? '#6C5CE7';
$phone1 = $S['phone1'] ?? '01XXXXXXXXX';
$phone2 = $S['phone2'] ?? '01XXXXXXXXX';
$bkash_number = $S['bkash_number'] ?? $phone1;
$nagad_number = $S['nagad_number'] ?? $phone1;
$rocket_number = $S['rocket_number'] ?? $phone1;
$bank_details = $S['bank_details'] ?? '';
$use_image = $S['use_image_logo'] ?? '0';
$logo_image = $S['logo_image'] ?? '';
$footer_text = $S['footer_text'] ?? 'বাংলা LMS | সর্বস্বত্ব সংরক্ষিত';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পেমেন্ট - <?= htmlspecialchars($site_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:<?=$primary_color?>;--g1:linear-gradient(135deg,<?=$primary_color?>,<?=$primary_color?>dd)}
        *{margin:0;padding:0;box-sizing:border-box}
        body{background:#f0f2f8;font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif;min-height:100vh}
        
        .navbar{background:white;box-shadow:0 2px 10px rgba(0,0,0,0.06);padding:12px 0}
        .navbar-brand{font-weight:800;font-size:1.2rem;background:var(--g1);-webkit-background-clip:text;-webkit-text-fill-color:transparent;text-decoration:none;display:flex;align-items:center;gap:8px}
        .navbar-brand img{height:34px}
        
        .container{max-width:700px;margin:0 auto;padding:30px 20px}
        
        .payment-card{background:white;border-radius:24px;padding:35px;box-shadow:0 15px 50px rgba(0,0,0,0.1)}
        .payment-header{text-align:center;margin-bottom:25px}
        .item-icon{width:70px;height:70px;border-radius:50%;background:var(--g1);display:inline-flex;align-items:center;justify-content:center;font-size:1.8rem;color:white;margin-bottom:15px}
        .price-tag{font-size:2.5rem;font-weight:800;color:var(--primary)}.price-tag.free{color:#11998e}
        .price-tag small{font-size:1rem;color:#888}
        
        .payment-methods{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px}
        .method-btn{flex:1;min-width:80px;padding:15px 10px;border:2px solid #e8eaef;border-radius:14px;text-align:center;cursor:pointer;transition:0.3s;background:white}
        .method-btn:hover,.method-btn.active{border-color:var(--primary);background:#f8f9ff}
        .method-btn i{font-size:1.5rem;display:block;margin-bottom:5px}
        .method-btn.bkash i{color:#e2136e}.method-btn.nagad i{color:#ef2222}.method-btn.rocket i{color:#8c3494}
        
        .form-control,select{width:100%;padding:12px 15px;border-radius:12px;border:2px solid #e8eaef;margin-bottom:10px;font-size:0.95rem;background:#fafbfd}
        .form-control:focus,select:focus{border-color:var(--primary);outline:none;background:white}
        label{font-weight:600;font-size:0.85rem;display:block;margin-bottom:4px;color:#444}
        
        .btn{font-weight:600;cursor:pointer;transition:0.3s;border-radius:50px;padding:14px 30px;border:none;font-size:1rem;width:100%}
        .btn-primary{background:var(--g1);color:white}.btn-primary:hover{transform:translateY(-3px);box-shadow:0 10px 25px rgba(108,92,231,0.35)}
        .btn-success{background:linear-gradient(135deg,#11998e,#38ef7d);color:#0d4d2b}
        
        .info-box{background:#f8f9ff;border-radius:14px;padding:18px;margin:15px 0;border:1px solid #e8e8ff}
        .info-box h6{color:var(--primary);margin-bottom:8px}
        .info-box p{margin:3px 0;font-size:0.9rem}
        
        .alert{border-radius:12px;padding:14px;margin-bottom:15px;font-size:0.9rem}
        .alert-info{background:#e8f0fe;color:#1967d2}
        .alert-success{background:#eaffea;color:#155724}
        
        .badge-auto{display:inline-block;padding:5px 14px;border-radius:20px;background:#d4f5e9;color:#11998e;font-size:0.75rem;font-weight:600}
        
        footer{background:#1a1a2e;color:white;text-align:center;padding:20px;margin-top:40px}
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container" style="display:flex;justify-content:space-between;align-items:center">
        <a href="index.php" class="navbar-brand">
            <?php if($use_image=='1' && !empty($logo_image) && file_exists('uploads/logo/'.$logo_image)): ?>
                <img src="uploads/logo/<?=$logo_image?>" alt="<?=htmlspecialchars($site_title)?>">
            <?php else: ?>
                <i class="fas <?=$logo_icon?> me-2"></i><?=htmlspecialchars($logo_text)?>
            <?php endif; ?>
        </a>
        <a href="dashboard.php" style="color:#555;text-decoration:none"><i class="fas fa-arrow-left me-1"></i> ফিরে যান</a>
    </div>
</nav>

<div class="container">
    
    <?php if(isset($_SESSION['success'])): ?>
        <div class="alert alert-success"><?=$_SESSION['success']?></div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    
    <div class="payment-card">
        <div class="payment-header">
            <div class="item-icon"><i class="fas fa-credit-card"></i></div>
            <h3>পেমেন্ট সম্পন্ন করুন</h3>
            <p class="text-muted"><?=htmlspecialchars($item_name)?></p>
            <div class="price-tag <?=$price==0?'free':''?>">
                <?=$price>0?'৳'.number_format($price):'বিনামূল্যে'?>
                <?php if($price>0): ?><small> টাকা</small><?php endif; ?>
            </div>
            <span class="badge-auto mt-2">⚡ সাথে সাথে এনরোল</span>
        </div>
        
        <?php if($price == 0): ?>
            <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: ?>
            <form method="POST" id="paymentForm">
                <label>পেমেন্ট মেথড সিলেক্ট করুন</label>
                <div class="payment-methods">
                    <div class="method-btn bkash active" onclick="selectMethod('bkash',this)">
                        <i class="fas fa-mobile-alt"></i> বিকাশ
                    </div>
                    <div class="method-btn nagad" onclick="selectMethod('nagad',this)">
                        <i class="fas fa-mobile-alt"></i> নগদ
                    </div>
                    <div class="method-btn rocket" onclick="selectMethod('rocket',this)">
                        <i class="fas fa-mobile-alt"></i> রকেট
                    </div>
                </div>
                <input type="hidden" name="payment_method" value="bkash" id="paymentMethod">
                
                <!-- Payment Info -->
                <div class="info-box" id="paymentInfo">
                    <h6><i class="fas fa-info-circle me-1"></i> বিকাশ পেমেন্ট তথ্য</h6>
                    <p><strong>বিকাশ নম্বর:</strong> <?=htmlspecialchars($bkash_number)?></p>
                    <p><strong>সেন্ড মানি</strong> করে নিচের ফর্মটি পূরণ করুন</p>
                </div>
                
                <label>আপনার ফোন নম্বর (যে নম্বর থেকে পেমেন্ট করবেন)</label>
                <input type="text" name="sender_phone" class="form-control" placeholder="01XXXXXXXXX" required value="<?=htmlspecialchars($user['phone']??'')?>">
                
                <label>ট্রানজেকশন আইডি</label>
                <input type="text" name="transaction_id" class="form-control" placeholder="TRXID লিখুন" required>
                
                <div class="alert alert-info">
                    <i class="fas fa-check-circle me-1"></i>
                    পেমেন্ট সাবমিট করার সাথে সাথে আপনার এনরোলমেন্ট অ্যাক্টিভ হবে। কোন অনুমোদনের প্রয়োজন নেই।
                </div>
                
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-lock me-2"></i> পেমেন্ট সাবমিট করুন
                </button>
            </form>
        <?php endif; ?>
    </div>
</div>

<footer>
    <p>&copy; <?=date('Y')?> <?=htmlspecialchars($footer_text)?></p>
</footer>

<script>
function selectMethod(method, el) {
    document.querySelectorAll('.method-btn').forEach(b => b.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('paymentMethod').value = method;
    
    const info = document.getElementById('paymentInfo');
    if(method === 'bkash') {
        info.innerHTML = '<h6><i class="fas fa-info-circle me-1"></i> বিকাশ পেমেন্ট তথ্য</h6><p><strong>বিকাশ নম্বর:</strong> <?=htmlspecialchars($bkash_number)?></p><p>সেন্ড মানি করে নিচের ফর্মটি পূরণ করুন</p>';
    } else if(method === 'nagad') {
        info.innerHTML = '<h6><i class="fas fa-info-circle me-1"></i> নগদ পেমেন্ট তথ্য</h6><p><strong>নগদ নম্বর:</strong> <?=htmlspecialchars($nagad_number)?></p><p>সেন্ড মানি করে নিচের ফর্মটি পূরণ করুন</p>';
    } else if(method === 'rocket') {
        info.innerHTML = '<h6><i class="fas fa-info-circle me-1"></i> রকেট পেমেন্ট তথ্য</h6><p><strong>রকেট নম্বর:</strong> <?=htmlspecialchars($rocket_number)?></p><p>সেন্ড মানি করে নিচের ফর্মটি পূরণ করুন</p>';
    }
}
</script>
</body>
</html>
<?php ob_end_flush(); ?>