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

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

// Get system name for branding
$system_name = get_system_name($pdo);

// Only logged-in students or admins
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] !== 'student' && $_SESSION['user_role'] !== 'admin')) {
    header('Location: ../login.php');
    exit();
}

// Get student ID (either from session or GET parameter for admin)
$student_id = 0;
if ($_SESSION['user_role'] === 'student') {
    // Get student from user
    $stmt = $pdo->prepare("SELECT id FROM students WHERE user_id=? LIMIT 1");
    $stmt->execute([$_SESSION['user_id']]);
    $student = $stmt->fetch();
    if (!$student) { 
        die('Student profile not found'); 
    }
    $student_id = $student['id'];
} else if ($_SESSION['user_role'] === 'admin' && isset($_GET['student_id'])) {
    $student_id = (int)$_GET['student_id'];
}

// Get student details
$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();
if (!$student) { 
    die('Student not found'); 
}

// Check if student has scholarship
$has_scholarship = ($student['scholarship'] === 'yes');

// If student has scholarship, redirect back with message
if ($has_scholarship) {
    $_SESSION['info_message'] = 'আপনি উপবৃত্তি পেয়েছেন। ফি পরিশোধের দরকার নেই।';
    header('Location: my_fees.php');
    exit();
}

// Calculate total due amount
$stmt = $pdo->prepare("SELECT SUM(amount - paid_amount) as total_due FROM fees WHERE student_id=? AND status IN ('pending', 'partial', 'overdue')");
$stmt->execute([$student_id]);
$result = $stmt->fetch();
$total_due = (float)($result['total_due'] ?? 0);

// If no due amount, redirect back
if ($total_due <= 0) {
    $_SESSION['info_message'] = 'আপনার কোন বকেয়া ফি নেই।';
    header('Location: my_fees.php');
    exit();
}

// Get amount from GET parameter or calculate total due
$amount = 0;
if (isset($_GET['amount'])) {
    $amount = (float)$_GET['amount'];
} else {
    $amount = $total_due;
}

// Check if amount is valid
if ($amount <= 0) {
    $_SESSION['error_message'] = 'No due amount found for payment';
    header('Location: my_fees.php');
    exit();
}

// Prevent students from making payments that exceed total due
if ($_SESSION['user_role'] === 'student' && $amount > $total_due) {
    $_SESSION['error_message'] = 'আপনি আপনার মোট বকেয়ার চেয়ে বেশি পরিমাণ পেমেন্ট করতে পারবেন না';
    header('Location: my_fees.php');
    exit();
}

// Check if payment gateways are enabled
$zashof = new ZashofPayment();
$zashof_enabled = $zashof->isEnabled();

$bKash = new bKashPayment();
$bKash_enabled = $bKash->isEnabled();

// Get current step (1: Enter mobile, 2: Enter PIN, 3: Enter OTP, 4: Confirm payment)
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;

// Process bKash payment initiation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Step 1: Enter mobile number
        if (isset($_POST['enter_mobile'])) {
            $bkash_number = trim($_POST['bkash_number'] ?? '');
            
            // Validate bKash number (Bangladeshi phone number format)
            if (empty($bkash_number) || !preg_match('/^(01[3-9]\d{8}|8801[3-9]\d{8})$/', $bkash_number)) {
                throw new Exception("Please enter a valid Bangladeshi mobile number for bKash");
            }
            
            // Format the number properly
            if (strpos($bkash_number, '880') === 0) {
                $bkash_number = '0' . substr($bkash_number, 3);
            }
            
            // Store in session for next steps
            $_SESSION['bkash_number'] = $bkash_number;
            
            // Redirect to PIN entry step
            header('Location: bKash_payment.php?amount=' . $amount . '&step=2');
            exit();
        }
        // Step 2: Enter PIN
        else if (isset($_POST['enter_pin'])) {
            $pin = trim($_POST['bkash_pin'] ?? '');
            
            // Validate PIN (4 digits)
            if (empty($pin) || !preg_match('/^\d{4}$/', $pin)) {
                throw new Exception("Please enter a valid 4-digit bKash PIN");
            }
            
            // Store in session for next steps
            $_SESSION['bkash_pin'] = $pin;
            
            // Generate a fake OTP for simulation
            $_SESSION['bkash_otp'] = rand(100000, 999999);
            
            // Redirect to OTP entry step
            header('Location: bKash_payment.php?amount=' . $amount . '&step=3');
            exit();
        }
        // Step 3: Enter OTP
        else if (isset($_POST['enter_otp'])) {
            $otp = trim($_POST['bkash_otp'] ?? '');
            
            // Validate OTP
            if (empty($otp) || $otp != ($_SESSION['bkash_otp'] ?? '')) {
                throw new Exception("Invalid OTP. Please try again.");
            }
            
            // Store in session for next steps
            $_SESSION['bkash_otp_verified'] = true;
            
            // Redirect to confirmation step
            header('Location: bKash_payment.php?amount=' . $amount . '&step=4');
            exit();
        }
        // Step 4: Confirm payment
        else if (isset($_POST['confirm_payment'])) {
            // If bKash direct integration is enabled and properly configured, use it
            if ($bKash_enabled) {
                // Prepare student info for payment gateway
                $student_info = [
                    'student_id' => $student['student_id'],
                    'name' => $student['first_name'] . ' ' . $student['last_name'],
                    'phone' => $_SESSION['bkash_number'] ?? ''
                ];
                
                // Create payment using bKash
                $payment = $bKash->createPayment($amount, $student_info);
                
                // Clear session data
                unset($_SESSION['bkash_number']);
                unset($_SESSION['bkash_pin']);
                unset($_SESSION['bkash_otp']);
                unset($_SESSION['bkash_otp_verified']);
                
                // Redirect to bKash payment page
                if (isset($payment['paymentUrl'])) {
                    header('Location: ' . $payment['paymentUrl']);
                    exit();
                } else {
                    throw new Exception("Failed to create bKash payment request. Please try again.");
                }
            } 
            // If Zashof is enabled, use it as fallback
            else if ($zashof_enabled) {
                // Prepare student info for payment gateway
                $student_info = [
                    'student_id' => $student['student_id'],
                    'name' => $student['first_name'] . ' ' . $student['last_name'],
                    'phone' => $_SESSION['bkash_number'] ?? ''
                ];
                
                // Get redirect URLs
                $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
                $redirect_url = 'http://' . $host . '/fees/zashof_success.php';
                $cancel_url = 'http://' . $host . '/fees/my_fees.php';
                
                // Create charge using Zashof
                $charge = $zashof->createCharge($amount, $student_info, $redirect_url, $cancel_url);
                
                // Clear session data
                unset($_SESSION['bkash_number']);
                unset($_SESSION['bkash_pin']);
                unset($_SESSION['bkash_otp']);
                unset($_SESSION['bkash_otp_verified']);
                
                // Redirect to payment gateway
                if (isset($charge['redirect_url'])) {
                    header('Location: ' . $charge['redirect_url']);
                    exit();
                } else {
                    throw new Exception("Failed to create payment request. Please try again.");
                }
            } else {
                // Fallback to manual process if no payment gateway is enabled
                // Generate a unique transaction reference
                $transaction_ref = 'BKASH_' . time() . '_' . $student_id;
                
                // Clear session data
                unset($_SESSION['bkash_number']);
                unset($_SESSION['bkash_pin']);
                unset($_SESSION['bkash_otp']);
                unset($_SESSION['bkash_otp_verified']);
                
                // Store success message and redirect to transaction submission page
                $_SESSION['success_message'] = 'আপনার পেমেন্ট রিকুয়েস্ট গৃহীত হয়েছে। এখন ট্রানজেকশন আইডি জমা দিন।';
                header('Location: submit_bkash_transaction.php');
                exit();
            }
        }
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bKash পেমেন্ট - <?php echo htmlspecialchars($system_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="../assets/css/style.css" rel="stylesheet">
    <style>
        .bkash-header {
            background-color: #E21919;
            color: white;
            padding: 15px;
            border-radius: 10px 10px 0 0;
            margin-bottom: 20px;
        }
        .bkash-logo {
            height: 40px;
            margin-right: 10px;
        }
        .bkash-card {
            border: 2px solid #E21919;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .bkash-input {
            border: 2px solid #E21919;
            border-radius: 5px;
        }
        .bkash-btn {
            background-color: #E21919;
            border-color: #E21919;
            color: white;
        }
        .bkash-btn:hover {
            background-color: #C11212;
            border-color: #C11212;
        }
        .progress-bar-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }
        .progress-bar-container::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #ddd;
            z-index: 1;
        }
        .progress-step {
            text-align: center;
            position: relative;
            z-index: 2;
        }
        .progress-step.active .step-number {
            background-color: #E21919;
            color: white;
        }
        .progress-step.completed .step-number {
            background-color: #28a745;
            color: white;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #ddd;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: bold;
        }
        .step-label {
            font-size: 12px;
            color: #666;
        }
        .otp-timer {
            color: #E21919;
            font-weight: bold;
        }
        .otp-message {
            background-color: #e9f7ef;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 0 4px 4px 0;
        }
    </style>
</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> <?php echo htmlspecialchars($system_name); ?></a>
        <div class="navbar-nav ms-auto">
            <?php if ($_SESSION['user_role'] === 'student'): ?>
                <a class="nav-link" href="my_fees.php"><i class="fas fa-arrow-left"></i> আমার ফি</a>
            <?php else: ?>
                <a class="nav-link" href="manage.php"><i class="fas fa-arrow-left"></i> ফি ম্যানেজ</a>
            <?php endif; ?>
            <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 bkash-card">
                <div class="bkash-header text-center">
                    <h4><img src="https://www.bkash.com/sites/all/themes/bkash/logo.svg" alt="bKash" class="bkash-logo"> bKash Payment</h4>
                </div>
                <div class="card-body">
                    <?php if (isset($error_message)): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> 
                            <?= htmlspecialchars($error_message) ?>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Progress Bar -->
                    <div class="progress-bar-container">
                        <div class="progress-step <?= $step >= 1 ? 'active' : '' ?> <?= $step > 1 ? 'completed' : '' ?>">
                            <div class="step-number">1</div>
                            <div class="step-label">মোবাইল</div>
                        </div>
                        <div class="progress-step <?= $step >= 2 ? 'active' : '' ?> <?= $step > 2 ? 'completed' : '' ?>">
                            <div class="step-number">2</div>
                            <div class="step-label">পিন</div>
                        </div>
                        <div class="progress-step <?= $step >= 3 ? 'active' : '' ?> <?= $step > 3 ? 'completed' : '' ?>">
                            <div class="step-number">3</div>
                            <div class="step-label">ওটিপি</div>
                        </div>
                        <div class="progress-step <?= $step >= 4 ? 'active' : '' ?>">
                            <div class="step-number">4</div>
                            <div class="step-label">কনফার্ম</div>
                        </div>
                    </div>
                    
                    <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> bKash Personal</p>
                                    <p class="mb-0"><strong>পেমেন্ট গেটওয়ে:</strong> 
                                        <?php if ($bKash_enabled): ?>
                                            Automatic (bKash Direct)
                                        <?php elseif ($zashof_enabled): ?>
                                            Automatic (Zashof)
                                        <?php else: ?>
                                            Manual
                                        <?php endif; ?>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Step 1: Mobile Number Entry -->
                    <?php if ($step == 1): ?>
                    <div class="text-center mb-4">
                        <h5><i class="fas fa-mobile-alt"></i> আপনার bKash নাম্বার প্রবেস করান</h5>
                        <p class="text-muted">bKash এর সাথে সংযুক্ত মোবাইল নাম্বার প্রবেস করান</p>
                    </div>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label for="bkash_number" class="form-label"><i class="fas fa-phone"></i> bKash নাম্বার</label>
                            <input type="text" class="form-control bkash-input" id="bkash_number" name="bkash_number" placeholder="01XXXXXXXXX" value="<?= htmlspecialchars($_SESSION['bkash_number'] ?? '') ?>" required>
                            <div class="form-text">bKash নাম্বার প্রবেস করান (যেমন: 017XXXXXXXX)</div>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button type="submit" name="enter_mobile" class="btn btn-success btn-lg bkash-btn">
                                <i class="fas fa-arrow-right"></i> পরবর্তী
                            </button>
                            <?php if ($_SESSION['user_role'] === 'student'): ?>
                                <a href="my_fees.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> আমার ফি-তে ফিরে যান
                                </a>
                            <?php else: ?>
                                <a href="manage.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> ফি ম্যানেজ-এ ফিরে যান
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                    <?php endif; ?>
                    
                    <!-- Step 2: PIN Entry -->
                    <?php if ($step == 2): ?>
                    <div class="text-center mb-4">
                        <h5><i class="fas fa-lock"></i> bKash পিন প্রবেস করান</h5>
                        <p class="text-muted">আপনার bKash একাউন্টের ৪ ডিজিটের পিন নাম্বার প্রবেস করান</p>
                    </div>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label for="bkash_pin" class="form-label"><i class="fas fa-key"></i> bKash পিন</label>
                            <input type="password" class="form-control bkash-input" id="bkash_pin" name="bkash_pin" placeholder="****" maxlength="4" required>
                            <div class="form-text">আপনার bKash একাউন্টের ৪ ডিজিটের পিন নাম্বার</div>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button type="submit" name="enter_pin" class="btn btn-success btn-lg bkash-btn">
                                <i class="fas fa-arrow-right"></i> পরবর্তী
                            </button>
                            <a href="bKash_payment.php?amount=<?= $amount ?>&step=1" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left"></i> পূর্ববর্তী
                            </a>
                        </div>
                    </form>
                    <?php endif; ?>
                    
                    <!-- Step 3: OTP Entry -->
                    <?php if ($step == 3): ?>
                    <div class="otp-message">
                        <i class="fas fa-sms"></i> <strong>OTP পাঠানো হয়েছে!</strong>
                        <p>আপনার মোবাইল নাম্বার <?= htmlspecialchars($_SESSION['bkash_number'] ?? '') ?> এ ৬ ডিজিটের ওটিপি কোড পাঠানো হয়েছে। দয়া করে নিচে প্রবেস করুন।</p>
                    </div>
                    
                    <div class="text-center mb-4">
                        <h5><i class="fas fa-shield-alt"></i> ওটিপি কোড প্রবেস করান</h5>
                        <p class="text-muted">আপনার মোবাইলে পাঠানো ৬ ডিজিটের ওটিপি কোড প্রবেস করান</p>
                        <p class="otp-timer">ওটিপি কোড ২ মিনিটের জন্য বৈধ</p>
                    </div>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label for="bkash_otp" class="form-label"><i class="fas fa-key"></i> ওটিপি কোড</label>
                            <input type="text" class="form-control bkash-input" id="bkash_otp" name="bkash_otp" placeholder="******" maxlength="6" required>
                            <div class="form-text">আপনার মোবাইল নাম্বার <?= htmlspecialchars(substr($_SESSION['bkash_number'] ?? '', 0, 3) . '***' . substr($_SESSION['bkash_number'] ?? '', -3)) ?> এ পাঠানো ওটিপি কোড</div>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button type="submit" name="enter_otp" class="btn btn-success btn-lg bkash-btn">
                                <i class="fas fa-arrow-right"></i> পরবর্তী
                            </button>
                            <a href="bKash_payment.php?amount=<?= $amount ?>&step=2" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left"></i> পূর্ববর্তী
                            </a>
                        </div>
                    </form>
                    <?php endif; ?>
                    
                    <!-- Step 4: Payment Confirmation -->
                    <?php if ($step == 4): ?>
                    <div class="text-center mb-4">
                        <h5><i class="fas fa-check-circle text-success"></i> পেমেন্ট নিশ্চিত করুন</h5>
                        <p class="text-muted">নিচের তথ্য যাচাই করে "পেমেন্ট করুন" বাটনে ক্লিক করুন</p>
                    </div>
                    
                    <div class="card bg-light mb-4">
                        <div class="card-body">
                            <h6 class="card-title">পেমেন্ট বিবরণ</h6>
                            <table class="table table-borderless mb-0">
                                <tr>
                                    <td><strong>পরিমাণ:</strong></td>
                                    <td class="text-end">৳<?= number_format($amount, 2) ?></td>
                                </tr>
                                <tr>
                                    <td><strong>প্রাপক:</strong></td>
                                    <td class="text-end">School Management System</td>
                                </tr>
                                <tr>
                                    <td><strong>মোবাইল:</strong></td>
                                    <td class="text-end"><?= htmlspecialchars($_SESSION['bkash_number'] ?? '') ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <form method="POST">
                        <div class="d-grid gap-2">
                            <button type="submit" name="confirm_payment" class="btn btn-success btn-lg bkash-btn">
                                <i class="fas fa-money-bill-wave"></i> পেমেন্ট করুন (৳<?= number_format($amount, 2) ?>)
                            </button>
                            <a href="bKash_payment.php?amount=<?= $amount ?>&step=3" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left"></i> পূর্ববর্তী
                            </a>
                        </div>
                    </form>
                    <?php endif; ?>
                </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>