<?php
session_start();

// Check if user is logged in and is a student
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'student') {
    header('Location: ../login.php');
    exit();
}

require_once '../config/database.php';

// Get student details
$stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section as class_section FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
$stmt->execute([$_SESSION['student_id']]);
$student = $stmt->fetch();

if (!$student) {
    header('Location: ../login.php');
    exit();
}

$message = '';
$fee_details = null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fee_id = $_POST['fee_id'];
    $payment_amount = $_POST['payment_amount'];
    $payment_method = $_POST['payment_method'];
    $transaction_id = $_POST['transaction_id'] ?? '';

    // Validate payment amount
    $fee_stmt = $pdo->prepare("SELECT * FROM fees WHERE id = ? AND student_id = ?");
    $fee_stmt->execute([$fee_id, $student['id']]);
    $fee_details = $fee_stmt->fetch();

    if (!$fee_details) {
        $message = 'অবৈধ ফি রেকর্ড!';
    } elseif ($payment_amount <= 0) {
        $message = 'পরিশোধের পরিমাণ অবশ্যই ধনাত্মক হতে হবে!';
    } elseif ($payment_amount > ($fee_details['amount'] - $fee_details['paid_amount'])) {
        $message = 'পরিশোধের পরিমাণ বকেয়া পরিমাণের চেয়ে বেশি হতে পারবে না!';
    } else {
        try {
            // Begin transaction
            $pdo->beginTransaction();

            // Update fee record
            $new_paid_amount = $fee_details['paid_amount'] + $payment_amount;
            $new_status = 'pending'; // Payment needs to be verified
            
            if ($new_paid_amount >= $fee_details['amount']) {
                $new_status = 'paid';
            } elseif ($new_paid_amount > 0) {
                $new_status = 'partial';
            }

            $update_fee = $pdo->prepare("UPDATE fees SET paid_amount = ?, status = ? WHERE id = ?");
            $update_fee->execute([$new_paid_amount, $new_status, $fee_id]);

            // Insert payment record
            $insert_payment = $pdo->prepare("
                INSERT INTO fee_payments (fee_id, student_id, amount, payment_method, transaction_id, payment_date, status) 
                VALUES (?, ?, ?, ?, ?, NOW(), 'pending')
            ");
            $insert_payment->execute([$fee_id, $student['id'], $payment_amount, $payment_method, $transaction_id]);

            $pdo->commit();
            $message = 'পেমেন্ট সাবমিট করা হয়েছে! এটি যাচাইয়ের পর আপডেট করা হবে।';
        } catch (Exception $e) {
            $pdo->rollback();
            $message = 'পেমেন্ট প্রক্রিয়ায় ত্রুটি হয়েছে: ' . $e->getMessage();
        }
    }
}

// Get fee details if fee_id is provided in URL
if (isset($_GET['fee_id'])) {
    $fee_id = $_GET['fee_id'];
    $fee_stmt = $pdo->prepare("SELECT f.*, ft.name as fee_type_name FROM fees f LEFT JOIN fee_types ft ON f.fee_type_id = ft.id WHERE f.id = ? AND f.student_id = ?");
    $fee_stmt->execute([$fee_id, $student['id']]);
    $fee_details = $fee_stmt->fetch();
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি পরিশোধ - <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></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@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif; 
            background-color: #f8f9fa;
        }
        .payment-card {
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../student_dashboard.php"><i class="fas fa-arrow-left"></i> ছাত্র ড্যাশবোর্ড</a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    <i class="fas fa-user-graduate"></i> <?php echo htmlspecialchars($_SESSION['user_name']); ?>
                </span>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <h2><i class="fas fa-credit-card"></i> ফি পরিশোধ</h2>
                <p>ছাত্র নাম: <strong><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></strong> | 
                   ছাত্র আইডি: <strong><?php echo htmlspecialchars($student['student_id']); ?></strong></p>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i> <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <?php if ($fee_details): ?>
            <div class="card payment-card">
                <div class="card-header bg-success text-white">
                    <h5><i class="fas fa-file-invoice"></i> ফি তথ্য</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>ফি টাইপ:</strong> <?php echo htmlspecialchars($fee_details['fee_type_name'] ?? $fee_details['description']); ?></p>
                            <p><strong>মোট ফি:</strong> ৳<?php echo number_format($fee_details['amount']); ?></p>
                            <p><strong>পরিশোধিত:</strong> ৳<?php echo number_format($fee_details['paid_amount']); ?></p>
                            <p><strong>বকেয়া:</strong> ৳<?php echo number_format($fee_details['amount'] - $fee_details['paid_amount']); ?></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>অবস্থা:</strong> 
                                <?php if ($fee_details['status'] == 'paid'): ?>
                                    <span class="badge bg-success">পরিশোধিত</span>
                                <?php elseif ($fee_details['status'] == 'partial'): ?>
                                    <span class="badge bg-warning">আংশিক পরিশোধ</span>
                                <?php elseif ($fee_details['status'] == 'overdue'): ?>
                                    <span class="badge bg-danger">অতিবর্তিত</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">মুলতুবি</span>
                                <?php endif; ?>
                            </p>
                            <p><strong>নির্ধারিত তারিখ:</strong> <?php echo date('d/m/Y', strtotime($fee_details['due_date'])); ?></p>
                            <p><strong>বিবরণ:</strong> <?php echo htmlspecialchars($fee_details['description'] ?? 'N/A'); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card payment-card">
                <div class="card-header bg-primary text-white">
                    <h5><i class="fas fa-money-bill-wave"></i> পেমেন্ট করুন</h5>
                </div>
                <div class="card-body">
                    <form method="POST" action="">
                        <input type="hidden" name="fee_id" value="<?php echo $fee_details['id']; ?>">
                        
                        <div class="mb-3">
                            <label for="payment_amount" class="form-label">পরিশোধের পরিমাণ (৳)</label>
                            <input type="number" class="form-control" id="payment_amount" name="payment_amount" 
                                   min="1" max="<?php echo $fee_details['amount'] - $fee_details['paid_amount']; ?>" 
                                   value="<?php echo $fee_details['amount'] - $fee_details['paid_amount']; ?>" required>
                            <div class="form-text">সর্বোচ্চ বকেয়া পরিমাণ: ৳<?php echo number_format($fee_details['amount'] - $fee_details['paid_amount']); ?></div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="payment_method" class="form-label">পেমেন্ট মাধ্যম</label>
                            <select class="form-select" id="payment_method" name="payment_method" required>
                                <option value="">পেমেন্ট মাধ্যম নির্বাচন করুন</option>
                                <option value="cash">নগদ</option>
                                <option value="bank">ব্যাংক ট্রান্সফার</option>
                                <option value="bkash">বিকাশ</option>
                                <option value="nagad">নগদ</option>
                                <option value="rocket">রকেট</option>
                                <option value="upay">উপায়</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="transaction_id" class="form-label">ট্রানজেকশন আইডি (যদি থাকে)</label>
                            <input type="text" class="form-control" id="transaction_id" name="transaction_id" placeholder="ট্রানজেকশন আইডি লিখুন">
                            <div class="form-text">বিকাশ, নগদ, রকেট ইত্যাদির ক্ষেত্রে ট্রানজেকশন আইডি দরকার</div>
                        </div>
                        
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-paper-plane"></i> পেমেন্ট সাবমিট করুন
                        </button>
                        <a href="student_fees.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> ফি তালিকায় ফিরুন
                        </a>
                    </form>
                </div>
            </div>
        <?php else: ?>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i> কোন ফি রেকর্ড নির্বাচন করা হয়নি।
                <a href="student_fees.php" class="btn btn-primary ms-2">ফি তালিকায় যান</a>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>