<?php
session_start();
require_once '../config/database.php';

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

// Get student
$stmt = $pdo->prepare("SELECT s.*, c.name as class_name FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.user_id=? LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch();
if (!$student) { die('Student not found'); }

// Get due fees
$stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id=? AND (amount - paid_amount) > 0 ORDER BY due_date ASC");
$stmt->execute([$student['id']]);
$due_fees = $stmt->fetchAll();

if (empty($due_fees)) {
    $_SESSION['info_message'] = 'কোনো বকেয়া ফি নেই।';
    header('Location: my_fees.php');
    exit();
}

// Handle payment initiation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected_fee_ids = $_POST['fee_ids'] ?? [];
    if (empty($selected_fee_ids)) {
        $error = 'অন্তত একটি ফি নির্বাচন করুন।';
    } else {
        $total = 0;
        $fee_details = [];
        foreach ($due_fees as $f) {
            if (in_array($f['id'], $selected_fee_ids)) {
                $due = (float)($f['amount'] - $f['paid_amount']);
                $total += $due;
                $fee_details[] = $f['fee_type'] . ($f['month'] ? ' - ' . $f['month'] : '');
            }
        }

        if ($total <= 0) {
            $error = 'নির্বাচিত ফির পরিমাণ সঠিক নয়।';
        } else {
            $cfg = require '../config/zinipay.php';
            if (empty($cfg['api_key'])) {
                // Fallback: load directly with current $pdo
                $s = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'zinipay_%'");
                while ($row = $s->fetch()) {
                    if ($row['setting_key'] === 'zinipay_api_key') $cfg['api_key'] = $row['setting_value'];
                    if ($row['setting_key'] === 'zinipay_mode')    $cfg['mode']    = $row['setting_value'];
                }
            }

            // Unique val_id for this transaction
            $val_id = 'STU-' . $student['id'] . '-' . time();

            // Store in session for callback verification
            $_SESSION['zinipay_val_id']     = $val_id;
            $_SESSION['zinipay_fee_ids']    = $selected_fee_ids;
            $_SESSION['zinipay_student_id'] = $student['id'];
            $_SESSION['zinipay_amount']     = $total;

            $payload = [
                'val_id'       => $val_id,
                'amount'       => $total,
                'currency'     => 'BDT',
                'description'  => implode(', ', $fee_details),
                'cus_name'     => $student['first_name'] . ' ' . $student['last_name'],
                'cus_email'    => !empty($student['email']) ? $student['email'] : 'student@zashof.com',
                'cus_phone'    => $student['phone'] ?? '',
                'redirect_url' => $cfg['redirect_url'],
                'cancel_url'   => (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/fees/zinipay_pay.php',
                'webhook_url'  => $cfg['webhook_url'],
                'metadata'     => [
                    'student_id' => $student['id'],
                    'fee_ids'    => $selected_fee_ids,
                ],
            ];

            $ch = curl_init($cfg['api_base'] . '/payment/create');
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => json_encode($payload),
                CURLOPT_HTTPHEADER     => [
                    'Content-Type: application/json',
                    'zini-api-key: ' . $cfg['api_key'],
                ],
            ]);
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $result = json_decode($response, true);

            if (in_array($http_code, [200, 201]) && !empty($result['payment_url'])) {
                $_SESSION['zinipay_invoice_id'] = $result['invoice_id'] ?? '';
                header('Location: ' . $result['payment_url']);
                exit();
            } else {
                $error = 'পেমেন্ট শুরু করতে সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।';
            }
        }
    }
}

$total_due = array_sum(array_map(fn($f) => (float)($f['amount'] - $f['paid_amount']), $due_fees));
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZiniPay পেমেন্ট</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Hind Siliguri', sans-serif; background: #f8f9fa; }
        .pay-card { max-width: 560px; margin: 2rem auto; }
        .fee-row { border: 1px solid #dee2e6; border-radius: 8px; padding: 10px 14px; margin-bottom: 8px; background: #fff; cursor: pointer; transition: border-color .2s; }
        .fee-row:hover, .fee-row.selected { border-color: #0d6efd; background: #f0f6ff; }
        .total-box { background: linear-gradient(135deg,#0d6efd,#6610f2); color:#fff; border-radius:10px; padding:14px 18px; }
        .zinipay-btn { background: linear-gradient(135deg,#e91e8c,#ff6b35); border:none; border-radius:25px; padding:12px 30px; font-size:1rem; font-weight:700; color:#fff; width:100%; }
        .zinipay-btn:hover { opacity:.9; color:#fff; }
        .zinipay-btn:disabled { opacity:.6; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <a class="nav-link text-white" href="my_fees.php"><i class="fas fa-arrow-left"></i> ফিরে যান</a>
    </div>
</nav>

<div class="container">
    <div class="pay-card">
        <div class="card shadow-sm border-0">
            <div class="card-header" style="background:linear-gradient(135deg,#e91e8c,#ff6b35); color:#fff; border-radius:12px 12px 0 0;">
                <h5 class="mb-0"><i class="fas fa-mobile-alt"></i> ZiniPay দিয়ে পেমেন্ট করুন</h5>
            </div>
            <div class="card-body">
                <div class="mb-3 p-2 bg-light rounded">
                    <strong><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></strong>
                    <span class="text-muted ms-2"><?= htmlspecialchars($student['class_name'] ?? '') ?></span>
                </div>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>

                <form method="POST">
                    <p class="fw-bold mb-2">ফি নির্বাচন করুন:</p>

                    <?php foreach ($due_fees as $f):
                        $due = (float)($f['amount'] - $f['paid_amount']);
                    ?>
                    <div class="fee-row" onclick="toggleFee(this, <?= $f['id'] ?>)">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <input type="checkbox" name="fee_ids[]" value="<?= $f['id'] ?>"
                                       id="fee_<?= $f['id'] ?>" class="form-check-input me-2 fee-check"
                                       onchange="updateTotal()" checked>
                                <label for="fee_<?= $f['id'] ?>" onclick="event.stopPropagation()">
                                    <strong><?= htmlspecialchars($f['fee_type']) ?></strong>
                                    <?= $f['month'] ? ' — ' . htmlspecialchars($f['month']) : '' ?>
                                </label>
                            </div>
                            <span class="text-danger fw-bold">৳<?= number_format($due, 2) ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <div class="total-box mt-3 mb-3 d-flex justify-content-between align-items-center">
                        <span class="fs-6">মোট পেমেন্ট</span>
                        <span class="fs-4 fw-bold" id="totalDisplay">৳<?= number_format($total_due, 2) ?></span>
                    </div>

                    <button type="submit" class="zinipay-btn" id="payBtn">
                        <i class="fas fa-lock me-2"></i> ZiniPay দিয়ে পেমেন্ট করুন
                    </button>
                    <p class="text-center text-muted small mt-2">
                        <i class="fas fa-shield-alt"></i> bKash, Nagad, Card সহ সব পদ্ধতিতে পেমেন্ট করা যাবে
                    </p>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    const dueFees = <?= json_encode(array_column($due_fees, 'amount', 'id')) ?>;
    const paidFees = <?= json_encode(array_column($due_fees, 'paid_amount', 'id')) ?>;

    function toggleFee(row, id) {
        const cb = document.getElementById('fee_' + id);
        cb.checked = !cb.checked;
        row.classList.toggle('selected', cb.checked);
        updateTotal();
    }

    function updateTotal() {
        let total = 0;
        document.querySelectorAll('.fee-check:checked').forEach(cb => {
            const id = cb.value;
            total += (parseFloat(dueFees[id]) - parseFloat(paidFees[id]));
        });
        document.getElementById('totalDisplay').textContent = '৳' + total.toFixed(2);
        document.getElementById('payBtn').disabled = total <= 0;
    }

    // Mark initially checked rows as selected
    document.querySelectorAll('.fee-check:checked').forEach(cb => {
        cb.closest('.fee-row').classList.add('selected');
    });
</script>
</body>
</html>
