<?php 
// Advanced Configuration
ini_set('display_errors', 1); error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
require_once 'db_connect.php';

include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

$success = ""; $error = "";

// ==========================================
// ⚙️ FETCH DYNAMIC DATA
// ==========================================
try {
    // ১. স্টুডেন্টের ইমেইল এবং কারেন্ট কোর্স আনা
    $stu_stmt = $pdo->prepare("SELECT email, course_id FROM students WHERE id = ?");
    $stu_stmt->execute([$student_id]);
    $student = $stu_stmt->fetch();
    $student_email = $student['email'];

    // ২. অ্যাডমিশন টেবিল থেকে 'Pay Later' (unpaid) রেকর্ড চেক করা
    $unpaid_stmt = $pdo->prepare("
        SELECT id, course_id, payable_fee, applied_date 
        FROM admissions 
        WHERE email COLLATE utf8mb4_unicode_ci = ? 
        AND payment_status = 'unpaid'
    ");
    $unpaid_stmt->execute([$student_email]);
    $unpaid_invoices = $unpaid_stmt->fetchAll(PDO::FETCH_ASSOC);

    // ৩. সব এক্টিভ কোর্স এবং তাদের ফি আনা (Dropdown এর জন্য)
    $courses = $pdo->query("SELECT id, title, fee FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) { $error = "Database Connection Error."; }

// ==========================================
// ⚙️ HANDLE TrxID SUBMISSION
// ==========================================
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_manual'])) {
    $c_id = (int)$_POST['selected_course_id'];
    $method = htmlspecialchars($_POST['payment_method']);
    $trx_id = trim(htmlspecialchars($_POST['trx_id']));
    $amount = trim(htmlspecialchars($_POST['amount']));
    $currency = htmlspecialchars($_POST['paid_currency']);

    if (!empty($trx_id) && !empty($amount)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO students_payments (student_id, amount, method, trx_id, status) VALUES (?, ?, ?, ?, 'pending')");
            $stmt->execute([$student_id, $amount, $method . " ($currency)", $trx_id]);
            $success = "MashaAllah! Your payment details submitted. Admin will verify it.";
        } catch (PDOException $e) { $error = "TrxID already exists or Error occurred."; }
    }
}

// ৪. পেমেন্ট হিস্ট্রি আনা
$history = $pdo->prepare("SELECT * FROM students_payments WHERE student_id = ? ORDER BY id DESC");
$history->execute([$student_id]);
$payments_history = $history->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root { --primary: #064e3b; --primary-dark: #022c22; --accent: #d4af37; --bg: #f8fafc; }
    .main-content { background-color: var(--bg); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* Action Card for Pay Later */
    .pay-later-card { background: #fff; border-left: 6px solid #ef4444; border-radius: 20px; padding: 20px; margin-bottom: 30px; box-shadow: 0 10px 25px rgba(239, 68, 68, 0.1); display: flex; justify-content: space-between; align-items: center; }
    .btn-pay-now { background: #ef4444; color: #fff; font-weight: 800; padding: 12px 25px; border-radius: 50px; text-decoration: none; font-size: 13px; transition: 0.3s; box-shadow: 0 5px 15px rgba(239, 68, 68, 0.3); }
    .btn-pay-now:hover { background: #b91c1c; transform: translateY(-2px); color: #fff; }

    /* Premium Fee Card */
    .fee-card { background: linear-gradient(135deg, var(--primary-dark), var(--primary)); color: #fff; border-radius: 24px; padding: 40px; text-align: center; border-bottom: 6px solid var(--accent); box-shadow: 0 15px 35px rgba(2, 44, 34, 0.2); margin-bottom: 40px; }
    .currency-select { background: rgba(255,255,255,0.15); color: var(--accent); border: 1px solid rgba(212, 175, 55, 0.4); border-radius: 50px; padding: 6px 18px; font-weight: 700; cursor: pointer; outline: none; }

    .payment-box { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; padding: 30px; box-shadow: 0 5px 20px rgba(0,0,0,0.02); height: 100%; }
    .status-pill { padding: 6px 14px; border-radius: 50px; font-size: 10px; font-weight: 800; text-transform: uppercase; }
    .status-pending { background: #fffbeb; color: #b45309; border: 1px solid #fde68a; }
    .status-verified, .status-approved { background: #ecfdf5; color: #059669; border: 1px solid #a7f3d0; }
    .status-rejected { background: #fef2f2; color: #ef4444; border: 1px solid #fecaca; }

    #sidebarToggle { display: none; }
    @media (max-width: 991.98px) {
        #sidebarToggle { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; background: #fff; border: 1px solid #ddd; border-radius: 10px; margin-right: 15px; color: var(--primary); }
        .pay-later-card { flex-direction: column; text-align: center; gap: 15px; }
    }
</style>

<div class="main-content p-3 p-md-5">
    
    <div class="d-flex align-items-center mb-5 fade-up">
        <div id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars"></i></div>
        <div>
            <h2 class="fw-bold text-dark mb-1">Billing & Invoices</h2>
            <p class="text-muted fw-semibold mb-0">Securely complete your payments</p>
        </div>
    </div>

    <?php if(!empty($unpaid_invoices)): ?>
    <div class="mb-4 fade-up">
        <h6 class="fw-bold text-danger mb-3"><i class="fas fa-exclamation-circle me-2"></i> PENDING ACTION</h6>
        <?php foreach($unpaid_invoices as $adm): ?>
        <div class="pay-later-card shadow-sm">
            <div>
                <span class="fw-bold text-dark" style="font-size: 16px;">Admission Payment: #<?= $adm['id'] ?></span><br>
                <small class="text-muted">You chose 'Pay Later' on <?= date('d M, Y', strtotime($adm['applied_date'])) ?>. Please complete this to activate your seat.</small>
            </div>
            <div class="text-md-end">
                <div class="fw-bold text-dark mb-2" style="font-size: 18px;">$<?= number_format($adm['payable_fee'], 2) ?></div>
                <a href="payment.php?id=<?= $adm['id'] ?>" class="btn-pay-now">PAY THIS INVOICE <i class="fas fa-arrow-right ms-2"></i></a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="fee-card fade-up">
        <div class="mb-3">
            <span class="text-white-50 small fw-bold text-uppercase me-2">Switch Currency:</span>
            <select id="currency_selector" class="currency-select" onchange="updateUI()">
                <option value="USD">USD ($)</option>
                <option value="BDT" selected>BDT (৳)</option>
            </select>
        </div>
        <h1 class="fw-bold mb-0" id="display_amount" style="font-size: 55px; color: var(--accent);">৳0</h1>
        <p class="text-white-50 small mt-2 fw-bold" id="course_label">Please select a course to pay</p>
    </div>

    <div class="row g-4">
        <div class="col-lg-6 fade-up">
            <div class="payment-box">
                <h5 class="fw-bold text-dark mb-4"><i class="fas fa-file-invoice text-success me-2"></i> Submit Payment Info</h5>
                <?php if($success) echo "<div class='alert alert-success fw-bold border-0 shadow-sm rounded-4 mb-3'>$success</div>"; ?>
                <?php if($error) echo "<div class='alert alert-danger fw-bold border-0 shadow-sm rounded-4 mb-3'>$error</div>"; ?>

                <form method="POST">
                    <input type="hidden" name="paid_currency" id="paid_currency" value="BDT">
                    
                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted">Select Course / Service</label>
                        <select name="selected_course_id" id="course_id" class="form-select py-3 rounded-3 border-2" onchange="updateUI()" required>
                            <option value="" data-fee="0">-- Select Course --</option>
                            <?php foreach($courses as $c): ?>
                                <option value="<?= $c['id'] ?>" data-fee="<?= $c['fee'] ?>" <?= ($c['id'] == $student['course_id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['title']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold text-muted">Payment Method Used</label>
                        <select name="payment_method" class="form-select py-3 rounded-3" required>
                            <option value="bKash">bKash (01815-244716)</option>
                            <option value="Nagad">Nagad (01815-244716)</option>
                            <option value="IBBL">Bank Transfer (Islami Bank)</option>
                        </select>
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-6">
                            <label class="form-label small fw-bold text-muted">Amount Sent</label>
                            <input type="number" name="amount" id="form_amount" class="form-control py-3" placeholder="0.00" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold text-muted">TrxID / Reference</label>
                            <input type="text" name="trx_id" class="form-control py-3" placeholder="e.g. 8N2KDF90A" required>
                        </div>
                    </div>

                    <button type="submit" name="submit_manual" class="btn btn-dark w-100 py-3 fw-bold rounded-3 shadow">SUBMIT TRANSACTION DETAILS</button>
                </form>
            </div>
        </div>

        <div class="col-lg-6 fade-up">
            <div class="payment-box">
                <h5 class="fw-bold text-dark mb-4"><i class="fas fa-history text-primary me-2"></i> Recent History</h5>
                <div class="table-responsive">
                    <table class="table align-middle">
                        <tbody>
                            <?php if(!empty($payments_history)): foreach($payments_history as $pay): ?>
                            <tr>
                                <td class="py-3">
                                    <div class="fw-bold text-dark">৳<?= number_format($pay['amount']) ?></div>
                                    <small class="text-muted fw-bold"><?= htmlspecialchars($pay['trx_id']) ?></small>
                                </td>
                                <td class="text-end py-3">
                                    <span class="status-pill status-<?= strtolower($pay['status']) ?>"><?= ucfirst($pay['status']) ?></span>
                                    <?php if($pay['status'] == 'rejected'): ?>
                                        <div class="text-danger small mt-1" style="font-size: 9px;"><?= htmlspecialchars($pay['note'] ?? 'Check TrxID') ?></div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                                <tr><td class="text-center py-5 text-muted fw-bold">No transactions recorded yet.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const rate = 125; // 1 USD = 125 BDT

    function updateUI() {
        const courseSelect = document.getElementById('course_id');
        const currency = document.getElementById('currency_selector').value;
        const display = document.getElementById('display_amount');
        const courseLabel = document.getElementById('course_label');
        const paidCurrencyField = document.getElementById('paid_currency');
        const formAmount = document.getElementById('form_amount');

        const selectedOption = courseSelect.options[courseSelect.selectedIndex];
        const baseUsd = parseFloat(selectedOption.getAttribute('data-fee')) || 0;
        const courseTitle = selectedOption.text;

        let finalAmount = 0;
        if(currency === 'BDT') {
            finalAmount = baseUsd * rate;
            display.innerText = '৳' + finalAmount.toLocaleString();
        } else {
            finalAmount = baseUsd;
            display.innerText = '$' + finalAmount.toLocaleString();
        }

        if(baseUsd > 0) {
            courseLabel.innerText = "Current fee for: " + courseTitle;
            formAmount.value = finalAmount; 
        } else {
            courseLabel.innerText = "Please select a course below";
            formAmount.value = "";
        }
        
        paidCurrencyField.value = currency;
    }

    window.onload = updateUI;
    document.getElementById('sidebarToggle')?.addEventListener('click', () => {
        document.getElementById('sidebarMenu').classList.toggle('active');
    });
</script>

<?php include 'includes/user_footer.php'; ?>