<?php
// Include all necessary helper files
require_once 'includes/db_connect.php';
require_once 'includes/mock_api.php';        // Needed for fetching bill details (simulation)
require_once 'includes/gateway_handler.php'; // Our new dynamic gateway handler for processing payments

// Security: Redirect to login page if user is not logged in
if (!isset($_SESSION["user_id"])) {
    header("location: login.php");
    exit;
}

// Initialize variables
$user_id = $_SESSION['user_id'];
$message = '';
$step = $_GET['step'] ?? 'select_biller'; // Determine the current step, default is 'select_biller'

// This block handles the final payment submission from the confirmation modal
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_payment'])) {
    $biller = $_POST['biller'];
    $account_number = $_POST['account_number'];
    $amount = (float)$_POST['amount'];
    $pin = $_POST['transaction_pin'];
    
    // Fetch user's data for PIN and balance verification
    $user_stmt = $conn->prepare("SELECT balance, transaction_pin FROM users WHERE id = ?");
    $user_stmt->bind_param("i", $user_id);
    $user_stmt->execute();
    $user = $user_stmt->get_result()->fetch_assoc();

    // --- Verification Sequence ---
    if (is_null($user['transaction_pin'])) {
        $message = '<div class="alert alert-danger">অনুগ্রহ করে প্রথমে প্রোফাইল পেজ থেকে আপনার লেনদেনের পিন সেট করুন।</div>';
    } elseif (!password_verify($pin, $user['transaction_pin'])) {
        $message = '<div class="alert alert-danger">আপনার দেওয়া পিনটি সঠিক নয়।</div>';
    } elseif ($user['balance'] < $amount) {
        $message = '<div class="alert alert-danger">আপনার একাউন্টে পর্যাপ্ত ব্যালেন্স নেই।</div>';
    } else {
        // --- If all checks pass, call the dynamic Gateway Handler ---
        $api_response = processBillPayment($conn, $biller, $account_number, $amount);
        
        if ($api_response['status'] === 'success') {
            // If the API call is successful, start a database transaction
            $conn->begin_transaction();
            try {
                // 1. Deduct balance from user's account
                $conn->query("UPDATE users SET balance = balance - $amount WHERE id = $user_id");
                
                $api_txn_id = $api_response['transactionId'];

                // 2. Log the payment in the 'bill_payments' table
                $conn->query("INSERT INTO bill_payments (user_id, biller_name, account_number, amount, status, api_transaction_id) VALUES ($user_id, '$biller', '$account_number', $amount, 'Success', '$api_txn_id')");
                
                // 3. Log the payment in the main 'transactions' table for the user's statement
                $desc = "Bill payment for $biller, Acc: $account_number (API Txn: $api_txn_id)";
                $conn->query("INSERT INTO transactions (user_id, type, amount, description) VALUES ($user_id, 'Bill Payment', $amount, '$desc')");
                
                $conn->commit();
                $step = 'receipt'; // Move to the final receipt step
            } catch (Exception $e) {
                $conn->rollback();
                $message = '<div class="alert alert-danger">একটি ডাটাবেজ সমস্যা হয়েছে। পেমেন্ট সম্পন্ন হয়নি।</div>';
            }
        } else {
            $message = '<div class="alert alert-danger">API গেটওয়ে থেকে পেমেন্ট ব্যর্থ হয়েছে: '.($api_response['message'] ?? 'Unknown Error').'</div>';
        }
    }
}
?>
<!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.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        body { background-color: #f0f2f5; font-family: 'Noto Sans Bengali', sans-serif; }
        .biller-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 1rem; }
        .biller-item { border: 1px solid #ddd; border-radius: 8px; text-align: center; padding: 1rem; text-decoration: none; color: #333; transition: all 0.2s; }
        .biller-item:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); transform: translateY(-5px); }
        .biller-item img { max-width: 60px; height: 60px; margin-bottom: 0.5rem; }
    </style>
</head>
<body>
<div class="container my-4" style="max-width: 600px;">
    <div class="d-flex align-items-center mb-4">
        <a href="index.php" class="text-dark fs-4 me-3 text-decoration-none"><i class="fas fa-arrow-left"></i></a>
        <h3 class="mb-0">বিল পরিশোধ করুন</h3>
    </div>

    <?php if(!empty($message)) echo $message; ?>

    <?php if ($step === 'select_biller'): ?>
    <div class="card"><div class="card-header">সার্ভিস প্রোভাইডার বাছাই করুন</div><div class="card-body"><div class="biller-grid">
        <a href="?step=enter_info&biller=DESCO Postpaid" class="biller-item"><img src="https://i.ibb.co/F8DThWf/desco.png" alt="DESCO"><span>DESCO Postpaid</span></a>
        <a href="?step=enter_info&biller=NESCO" class="biller-item"><img src="https://i.ibb.co/wJv3w1L/nesco.png" alt="NESCO"><span>NESCO</span></a>
        <a href="?step=enter_info&biller=Dhaka WASA" class="biller-item"><img src="https://i.ibb.co/yQjJ6yN/wasa.png" alt="WASA"><span>Dhaka WASA</span></a>
    </div></div></div>
    <?php endif; ?>

    <?php if ($step === 'enter_info'): $biller = htmlspecialchars($_GET['biller']); ?>
    <div class="card"><div class="card-header">আপনি "<?php echo $biller; ?>" বাছাই করেছেন</div><div class="card-body">
        <form method="POST" action="?step=confirm_bill"><p>টেস্ট করার জন্য একাউন্ট নম্বর `123456789` ব্যবহার করুন।</p><input type="hidden" name="biller" value="<?php echo $biller; ?>"><div class="mb-3"><label class="form-label">একাউন্ট/কনজিউমার নম্বর</label><input type="text" name="account_number" class="form-control" required></div><button type="submit" name="fetch_bill" class="btn btn-primary w-100">বিল দেখুন</button></form>
    </div></div>
    <?php endif; ?>

    <?php if ($step === 'confirm_bill' && isset($_POST['fetch_bill'])): 
        $biller = htmlspecialchars($_POST['biller']); $account_number = htmlspecialchars($_POST['account_number']);
        $bill_details = fetchBillDetailsAPI($biller, $account_number);
    ?>
    <div class="card"><div class="card-header">বিল কনফার্ম করুন</div><div class="card-body">
    <?php if ($bill_details['status'] === 'success'): ?>
        <h5>বিল বিবরণী</h5>
        <ul class="list-group list-group-flush mb-3">
            <li class="list-group-item d-flex justify-content-between"><strong>গ্রাহকের নাম:</strong> <span><?php echo $bill_details['customerName']; ?></span></li>
            <li class="list-group-item d-flex justify-content-between"><strong>বিলের পরিমাণ:</strong> <span class="fs-5 fw-bold text-danger">৳<?php echo number_format($bill_details['amount'], 2); ?></span></li>
            <li class="list-group-item d-flex justify-content-between"><strong>শেষ তারিখ:</strong> <span><?php echo $bill_details['dueDate']; ?></span></li>
        </ul>
        <form method="POST" action="pay_bill.php">
            <input type="hidden" name="biller" value="<?php echo $biller; ?>">
            <input type="hidden" name="account_number" value="<?php echo $account_number; ?>">
            <input type="hidden" name="amount" value="<?php echo $bill_details['amount']; ?>">
            <div class="mb-3">
                <label class="form-label">আপনার ৪-সংখ্যার লেনদেন পিন দিন</label>
                <input type="password" name="transaction_pin" class="form-control" inputmode="numeric" maxlength="4" required>
            </div>
            <button type="submit" name="confirm_payment" class="btn btn-success w-100">পেমেন্ট নিশ্চিত করুন</button>
        </form>
    <?php else: ?>
        <div class="alert alert-warning"><?php echo $bill_details['message']; ?></div><a href="?step=enter_info&biller=<?php echo $biller; ?>" class="btn btn-secondary">আবার চেষ্টা করুন</a>
    <?php endif; ?>
    </div></div>
    <?php endif; ?>

    <?php if ($step === 'receipt'): ?>
    <div class="card text-center"><div class="card-body p-4"><i class="fas fa-check-circle text-success fa-4x mb-3"></i>
        <h4 class="card-title">পেমেন্ট সফল হয়েছে</h4><p class="card-text">আপনার বিল পেমেন্ট রিকুয়েস্ট সফলভাবে সম্পন্ন হয়েছে।</p>
        <ul class="list-group list-group-flush text-start mb-3">
            <li class="list-group-item d-flex justify-content-between"><strong>সার্ভিস:</strong><span><?php echo htmlspecialchars($biller); ?></span></li>
            <li class="list-group-item d-flex justify-content-between"><strong>একাউন্ট নম্বর:</strong><span><?php echo htmlspecialchars($account_number); ?></span></li>
            <li class="list-group-item d-flex justify-content-between"><strong>পরিমাণ:</strong><span>৳<?php echo number_format($amount, 2); ?></span></li>
            <li class="list-group-item d-flex justify-content-between"><strong>ট্রানজেকশন আইডি:</strong><span><?php echo htmlspecialchars($api_txn_id); ?></span></li>
        </ul>
        <a href="index.php" class="btn btn-primary">ড্যাশবোর্ডে ফিরে যান</a>
    </div></div>
    <?php endif; ?>
</div>
</body>
</html>