<?php
// Debugging (Remove in production)
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'db_connect.php';

if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$admission_id = (int)$_GET['id'];
$msg = ""; $msgType = "";

// 1. Fetch Application Details and Payable Fee
try {
    $stmt = $pdo->prepare("
        SELECT a.*, c.title as course_title 
        FROM admissions a 
        JOIN courses c ON a.course_id = c.id 
        WHERE a.id = ?
    ");
    $stmt->execute([$admission_id]);
    $admission = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admission) { die("Application not found."); }

    // Set payable amount from admissions table (This is what we saved in step 1)
    $payable_amount = $admission['payable_fee'] ?? 0;

} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

// 2. Handle Payment Form Submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_payment'])) {
    $payment_method = htmlspecialchars($_POST['payment_method']);
    $transaction_id = htmlspecialchars(trim($_POST['transaction_id']));
    $paid_currency = htmlspecialchars($_POST['paid_currency']); 
    
    // Screenshot Upload
    $screenshot_path = "";
    if (isset($_FILES['payment_screenshot']) && $_FILES['payment_screenshot']['error'] == 0) {
        $upload_dir = 'uploads/payments/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        
        $ext = strtolower(pathinfo($_FILES['payment_screenshot']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ["jpg", "jpeg", "png"])) {
            $file_name = "pay_" . $admission_id . "_" . time() . "." . $ext;
            if (move_uploaded_file($_FILES["payment_screenshot"]["tmp_name"], $upload_dir . $file_name)) {
                $screenshot_path = $upload_dir . $file_name;
            }
        } else {
            $msg = "Screenshot must be an image (JPG/PNG)."; $msgType = "danger";
        }
    }

    if (empty($msg)) {
        if (!empty($payment_method) && !empty($transaction_id) && !empty($screenshot_path)) {
            try {
                $update = $pdo->prepare("UPDATE admissions SET payment_method = ?, transaction_id = ?, payment_screenshot = ?, payment_status = 'pending' WHERE id = ?");
                $update->execute([$payment_method . " (" . $paid_currency . ")", $transaction_id, $screenshot_path, $admission_id]);
                
                $msg = "Your payment information has been submitted successfully! You will receive a confirmation email once verified.";
                $msgType = "success";
                
                $admission['payment_status'] = 'pending'; 
            } catch (PDOException $e) {
                $msg = "Failed to update payment information."; $msgType = "danger";
            }
        } else {
            $msg = "Please provide the Payment Method, Transaction ID, and a Screenshot."; $msgType = "warning";
        }
    }
}

include 'header.php';
?>

<style>
    :root {
        --primary: #064e3b;        
        --primary-light: #059669;  
        --primary-dark: #022c22;   
        --accent: #d4af37;         
        --white: #ffffff;          
        --bg-soft: #f8fafc;
    }
    
    body { background-color: var(--bg-soft); font-family: 'Outfit', sans-serif; overflow-x: hidden; }
    
    .payment-wrapper { max-width: 900px; margin: 60px auto; background: var(--white); padding: 50px; border-radius: 20px; box-shadow: 0 15px 40px rgba(0,0,0,0.06); border-top: 8px solid var(--accent); }
    
    .fee-box { background: linear-gradient(135deg, var(--primary-dark), var(--primary)); color: var(--white); padding: 35px; border-radius: 15px; text-align: center; margin-bottom: 40px; border-left: 6px solid var(--accent); box-shadow: 0 10px 20px rgba(2, 44, 34, 0.15); position: relative; }
    
    /* Currency Selector Styling */
    .currency-selector-wrap { display: inline-flex; align-items: center; background: rgba(255,255,255,0.1); padding: 5px 15px; border-radius: 50px; margin-bottom: 15px; border: 1px solid rgba(212, 175, 55, 0.4); flex-wrap: wrap; justify-content: center; }
    .currency-select { background: transparent; color: var(--accent); border: none; font-weight: 700; font-size: 16px; outline: none; cursor: pointer; padding-left: 5px; }
    .currency-select option { background: var(--primary-dark); color: var(--white); }

    .info-card { border: 1px solid #e2e8f0; border-radius: 15px; padding: 25px; background: var(--white); height: 100%; transition: 0.3s; }
    
    .bank-box { background: rgba(6, 78, 59, 0.03); border: 2px dashed #cbd5e1; }
    .bank-box h5 { color: var(--primary-dark); font-weight: 800; border-bottom: 2px solid #e2e8f0; padding-bottom: 12px; margin-bottom: 15px; }
    .bank-detail-row { display: flex; justify-content: space-between; margin-bottom: 8px; border-bottom: 1px dashed #e2e8f0; padding-bottom: 8px; }
    .bank-detail-row:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
    .bank-detail-label { color: #64748b; font-weight: 600; font-size: 14px; }
    .bank-detail-value { color: var(--primary-dark); font-weight: 700; font-size: 14.5px; text-align: right; }

    .form-label { font-weight: 700; color: var(--primary-dark); font-size: 15px; margin-bottom: 8px; }
    .form-control, .form-select { border-radius: 10px; padding: 14px 15px; border: 2px solid #e2e8f0; background-color: var(--bg-soft); transition: 0.3s; font-size: 15px; }
    .form-control:focus, .form-select:focus { border-color: var(--primary); background-color: var(--white); box-shadow: 0 0 0 0.25rem rgba(6, 78, 59, 0.1); }
    
    .btn-submit { background: var(--accent); color: var(--primary-dark); padding: 16px; border-radius: 50px; font-weight: 800; font-size: 18px; border: none; transition: 0.3s; text-transform: uppercase; letter-spacing: 1px; }
    .btn-submit:hover { background: #c29d2b; transform: translateY(-3px); box-shadow: 0 10px 25px rgba(212, 175, 55, 0.4); }
    .btn-later { background: #f1f5f9; color: #64748b; padding: 16px 30px; border-radius: 50px; font-weight: 700; text-decoration: none; transition: 0.3s; border: 2px solid #e2e8f0; }
    .btn-later:hover { background: #e2e8f0; color: var(--primary-dark); }

    /* 📱 MOBILE RESPONSIVE FIXES 📱 */
    @media (max-width: 768px) {
        .payment-wrapper {
            margin: 20px 10px 40px; 
            padding: 25px 20px; 
        }
        .fee-box {
            padding: 20px 15px; 
            margin-bottom: 25px;
        }
        #display_amount {
            font-size: 34px !important; 
        }
        .currency-selector-wrap {
            font-size: 13px;
            padding: 5px 10px;
        }
        .currency-select {
            font-size: 14px;
        }
        .info-card {
            padding: 15px; 
        }
        .bank-detail-row {
            flex-direction: column; 
            align-items: flex-start;
            gap: 2px;
        }
        .bank-detail-value {
            text-align: left; 
            font-size: 14px;
        }
        .form-box-wrapper {
            padding: 20px 15px !important; 
        }
        .btn-submit, .btn-later {
            width: 100%; 
            text-align: center;
            font-size: 15px;
            padding: 14px;
        }
    }
</style>

<div class="container pb-5 px-md-3 px-2">
    <div class="payment-wrapper">
        <div class="text-center mb-md-5 mb-4">
            <h2 class="fw-bold fs-3" style="color: var(--primary-dark);"><i class="fas fa-wallet me-2" style="color: var(--accent);"></i> Payment Confirmation</h2>
            <p class="text-muted fs-6">Your enrollment application has been received. Please complete your payment to proceed.</p>
        </div>

        <?php if($msg): ?>
            <div class="alert alert-<?= $msgType ?> border-0 shadow-sm rounded-3 fw-bold p-3 mb-4 fs-6">
                <?= $msg ?>
            </div>
        <?php endif; ?>

        <?php if($admission['payment_status'] == 'unpaid'): ?>
            
            <div class="fee-box">
                <div class="currency-selector-wrap">
                    <i class="fas fa-globe me-2 text-white-50"></i>
                    <span class="text-white-50 small text-uppercase fw-bold me-2">Pay In:</span>
                    <select id="currency_selector" class="currency-select" onchange="convertCurrency()">
                        <option value="USD" selected>USD (Dollar)</option>
                        <option value="BDT">BDT (Taka)</option>
                        <option value="EUR">EUR (Euro)</option>
                        <option value="GBP">GBP (Pound)</option>
                    </select>
                </div>
                
                <h1 class="fw-bold mb-0" style="color: var(--accent); font-size: 45px;" id="display_amount">Loading...</h1>
                <small class="text-white-50 mt-3 d-block"><i class="fas fa-info-circle me-1"></i> Please send the exact amount using any of the methods below.</small>
            </div>

            <div class="row g-4 mb-4">
                
                <div class="col-lg-5">
                    <div class="info-card text-center">
                        <h5 class="fw-bold text-dark mb-3 border-bottom pb-2 fs-5">Mobile Banking (BD)</h5>
                        
                        <div class="d-flex align-items-center justify-content-center gap-3 mb-3">
                            <img src="https://freelogopng.com/images/all_img/1656234841bkash-icon-png.png" height="30" alt="bKash">
                            <div class="text-start">
                                <h6 class="fw-bold text-dark mb-0 fs-6">01815244716</h6>
                                <small class="text-muted fw-bold" style="font-size: 12px;">bKash (Personal)</small>
                            </div>
                        </div>
                        
                        <div class="d-flex align-items-center justify-content-center gap-3">
                            <img src="https://freelogopng.com/images/all_img/1679248787Nagad-Logo.png" height="30" alt="Nagad">
                            <div class="text-start">
                                <h6 class="fw-bold text-dark mb-0 fs-6">01815244716</h6>
                                <small class="text-muted fw-bold" style="font-size: 12px;">Nagad (Personal)</small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-7">
                    <div class="info-card bank-box">
                        <h5 class="fs-5"><i class="fas fa-university me-2 text-success"></i> Bank Transfer</h5>
                        
                        <div class="bank-detail-row">
                            <span class="bank-detail-label">Bank Name</span>
                            <span class="bank-detail-value">Islami Bank Bangladesh PLC</span>
                        </div>
                        <div class="bank-detail-row">
                            <span class="bank-detail-label">Account Name</span>
                            <span class="bank-detail-value">Md Nasrullah</span>
                        </div>
                        <div class="bank-detail-row">
                            <span class="bank-detail-label">Account Number</span>
                            <span class="bank-detail-value" style="color: #059669;">20507400200102709</span>
                        </div>
                        <div class="bank-detail-row">
                            <span class="bank-detail-label">Branch</span>
                            <span class="bank-detail-value">Moylapota Sub Branch</span>
                        </div>
                        <div class="bank-detail-row">
                            <span class="bank-detail-label">Routing Number</span>
                            <span class="bank-detail-value">125470223</span>
                        </div>
                        <div class="bank-detail-row">
                            <span class="bank-detail-label">SWIFT Code</span>
                            <span class="bank-detail-value">IBBLBDDH</span>
                        </div>
                        <div class="bank-detail-row mt-2 pt-2 border-top">
                            <span class="bank-detail-label">Address</span>
                            <span class="bank-detail-value text-muted" style="font-size: 13px;">Tootpara Circular Road, Khulna<br>Mobile: 01951755033</span>
                        </div>
                    </div>
                </div>
            </div>

            <form action="" method="POST" enctype="multipart/form-data">
                
                <input type="hidden" name="paid_currency" id="paid_currency" value="USD">

                <div class="row g-4 p-4 rounded-4 form-box-wrapper" style="background: var(--bg-soft); border: 1px solid #e2e8f0;">
                    
                    <div class="col-md-12 mb-1">
                        <h5 class="fw-bold" style="color: var(--primary-dark);">Submit Payment Details</h5>
                        <p class="text-muted small mb-0">After making the transfer, please provide the details below for verification.</p>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Payment Method Used <span class="text-danger">*</span></label>
                        <select name="payment_method" class="form-select" required>
                            <option value="">-- Select Method --</option>
                            <option value="bKash">bKash</option>
                            <option value="Nagad">Nagad</option>
                            <option value="Bank Transfer (Islami Bank)">Bank Transfer (Islami Bank)</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Transaction ID / Reference <span class="text-danger">*</span></label>
                        <input type="text" name="transaction_id" class="form-control" placeholder="e.g. 9J6A8XYZ or Bank Ref" required>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label">Payment Receipt / Screenshot <span class="text-danger">*</span></label>
                        <input type="file" name="payment_screenshot" class="form-control p-2 bg-white" accept="image/jpeg, image/png" required>
                        <small class="text-muted mt-1 d-block">Upload a clear photo or screenshot of your successful transaction.</small>
                    </div>
                </div>

                <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mt-4 gap-3">
                    <a href="index.php" class="btn-later text-center w-100 w-md-auto">
                        I'll Pay Later <i class="fas fa-arrow-right ms-2"></i>
                    </a>
                    
                    <button type="submit" name="submit_payment" class="btn-submit w-100 w-md-auto px-5 shadow-sm">
                        Submit Payment <i class="fas fa-check-circle ms-2"></i>
                    </button>
                </div>
            </form>

        <?php else: ?>
            <div class="text-center py-5">
                <i class="fas fa-check-circle fa-4x mb-3 text-success"></i>
                <h3 class="fw-bold fs-4" style="color: var(--primary-dark);">Payment Received</h3>
                <p class="text-muted fs-6">Your payment is currently under review by our administration. You will be notified shortly.</p>
                <a href="index.php" class="btn btn-outline-secondary rounded-pill px-5 py-2 fw-bold mt-3">Return to Homepage</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    const baseUsdPrice = <?= $payable_amount ?>;
    
    const exchangeRates = {
        'USD': 1.00,
        'BDT': 125.00,  
        'EUR': 0.92,    
        'GBP': 0.79     
    };

    const symbols = {
        'USD': '$',
        'BDT': '৳ ',
        'EUR': '€',
        'GBP': '£'
    };

    function convertCurrency() {
        const selectedCurrency = document.getElementById('currency_selector').value;
        const rate = exchangeRates[selectedCurrency];
        const symbol = symbols[selectedCurrency];
        
        const convertedPrice = baseUsdPrice * rate;
        
        let formattedPrice = "";
        if(selectedCurrency === 'BDT') {
            formattedPrice = convertedPrice.toLocaleString('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
        } else {
            formattedPrice = convertedPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
        
        document.getElementById('display_amount').innerText = symbol + formattedPrice;
        document.getElementById('paid_currency').value = selectedCurrency;
    }

    window.onload = function() {
        if(document.getElementById('currency_selector')) {
            convertCurrency();
        }
    };
</script>

<?php include 'footer.php'; ?>