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

// Handle both GET and POST requests
$transaction_id = $_GET['transaction_id'] ?? $_POST['transaction_id'] ?? '';
$status = $_GET['status'] ?? $_POST['status'] ?? '';

if (empty($transaction_id)) {
    $_SESSION['error_message'] = 'Invalid transaction. No transaction ID provided.';
    header('Location: my_fees.php');
    exit();
}

try {
    $zashof = new ZashofPayment();
    
    if (!$zashof->isEnabled()) {
        throw new Exception("Payment system is currently disabled. Please contact administrator.");
    }
    
    // Verify payment
    $verification = $zashof->verifyPayment($transaction_id);
    
    if (isset($verification['status']) && $verification['status'] === 'success') {
        // Payment successful
        $payment_data = $verification['data'] ?? [];
        $student_id = $payment_data['metadata']['student_id'] ?? 0;
        $amount = $payment_data['amount'] ?? 0;
        
        if ($student_id > 0 && $amount > 0) {
            // Update fee records
            $pdo->beginTransaction();
            
            try {
                // Update or create a fee payment record
                $stmt = $pdo->prepare("
                    INSERT INTO fee_payments (amount, payment_method, transaction_id, payment_date, remarks) 
                    VALUES (?, 'online', ?, CURDATE(), ?)
                    ON DUPLICATE KEY UPDATE 
                    amount = VALUES(amount), 
                    payment_method = VALUES(payment_method),
                    payment_date = VALUES(payment_date),
                    remarks = VALUES(remarks)
                ");
                $stmt->execute([
                    $amount, 
                    $transaction_id, 
                    'Payment successful via Zashof for student ID: ' . $student_id
                ]);
                
                // Update fee records (distribute payment across due fees)
                $stmt = $pdo->prepare("
                    SELECT id, amount, paid_amount 
                    FROM fees 
                    WHERE student_id = ? AND status IN ('pending', 'partial', 'overdue') 
                    ORDER BY due_date ASC
                ");
                $stmt->execute([$student_id]);
                $due_fees = $stmt->fetchAll();
                
                $remaining_amount = $amount;
                
                foreach ($due_fees as $fee) {
                    if ($remaining_amount <= 0) break;
                    
                    $due_amount = $fee['amount'] - $fee['paid_amount'];
                    $payment_amount = min($remaining_amount, $due_amount);
                    
                    $new_paid_amount = $fee['paid_amount'] + $payment_amount;
                    $new_status = ($new_paid_amount >= $fee['amount']) ? 'paid' : 'partial';
                    
                    $stmt = $pdo->prepare("
                        UPDATE fees 
                        SET paid_amount = ?, status = ?, paid_date = IF(paid_date IS NULL, CURDATE(), paid_date)
                        WHERE id = ?
                    ");
                    $stmt->execute([$new_paid_amount, $new_status, $fee['id']]);
                    
                    $remaining_amount -= $payment_amount;
                }
                
                $pdo->commit();
                
                // Set success message
                $_SESSION['success_message'] = 'পেমেন্ট সফলভাবে সম্পন্ন হয়েছে! আপনার লেনদেন আইডি: ' . $transaction_id;
            } catch (Exception $e) {
                $pdo->rollBack();
                throw new Exception("Failed to update fee records: " . $e->getMessage());
            }
        } else {
            throw new Exception("Invalid payment data received");
        }
    } else {
        // Payment failed
        throw new Exception("Payment verification failed: " . ($verification['message'] ?? 'Unknown error'));
    }
} catch (Exception $e) {
    $_SESSION['error_message'] = 'পেমেন্ট ব্যর্থ হয়েছে: ' . $e->getMessage();
    header('Location: my_fees.php');
    exit();
}

// Get student info for display
$student = null;
if (isset($student_id) && $student_id > 0) {
    $stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.id=? LIMIT 1");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পেমেন্ট সফল</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="../assets/css/style.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
        <div class="navbar-nav ms-auto">
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>
</nav>

<div class="container-fluid mt-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5><i class="fas fa-check-circle"></i> পেমেন্ট সফল!</h5>
                </div>
                <div class="card-body">
                    <div class="text-center mb-4">
                        <i class="fas fa-check-circle text-success" style="font-size: 4rem;"></i>
                        <h3 class="mt-3">অভিনন্দন!</h3>
                        <p class="lead">আপনার পেমেন্ট সফলভাবে সম্পন্ন হয়েছে</p>
                    </div>
                    
                    <?php if ($student): ?>
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title"><i class="fas fa-user-graduate"></i> শিক্ষার্থীর তথ্য</h6>
                                    <p class="mb-1"><strong>নাম:</strong> <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></p>
                                    <p class="mb-1"><strong>আইডি:</strong> <?= htmlspecialchars($student['student_id']) ?></p>
                                    <p class="mb-1"><strong>ক্লাস:</strong> <?= htmlspecialchars(($student['class_name'] ?? '') . ' - ' . ($student['section'] ?? '')) ?></p>
                                    <?php if (!empty($student['roll_number'])): ?>
                                        <p class="mb-0"><strong>রোল নম্বর:</strong> <?= htmlspecialchars($student['roll_number']) ?></p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="card bg-info text-white">
                                <div class="card-body">
                                    <h6 class="card-title"><i class="fas fa-receipt"></i> লেনদেনের বিবরণ</h6>
                                    <p class="mb-1"><strong>পরিমাণ:</strong> ৳<?= number_format($amount, 2) ?></p>
                                    <p class="mb-1"><strong>লেনদেন আইডি:</strong> <?= htmlspecialchars($transaction_id) ?></p>
                                    <p class="mb-0"><strong>অবস্থা:</strong> <span class="badge bg-success">সফল</span></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="alert alert-info">
                        <h6><i class="fas fa-info-circle"></i> গুরুত্বপূর্ণ তথ্য</h6>
                        <ul>
                            <li>আপনার পেমেন্ট রেকর্ড সিস্টেমে সফলভাবে আপডেট করা হয়েছে</li>
                            <li>এই লেনদেন আইডি ভবিষ্যতে রেফারেন্সের জন্য সংরক্ষণ করুন: <strong><?= htmlspecialchars($transaction_id) ?></strong></li>
                            <li>আপনি যেকোন সময় আপনার পেমেন্ট হিস্টোরি "আমার ফি" পেজে দেখতে পারবেন</li>
                        </ul>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'student'): ?>
                            <a href="my_fees.php" class="btn btn-primary btn-lg">
                                <i class="fas fa-money-bill-wave"></i> আমার ফি দেখুন
                            </a>
                        <?php else: ?>
                            <a href="manage.php" class="btn btn-primary btn-lg">
                                <i class="fas fa-tachometer-alt"></i> ড্যাশবোর্ডে ফিরে যান
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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