<?php
session_start();
require_once '../db.php'; // Your database connection file

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

$mid = $_SESSION['Mid'];

// Fetch total saving amount for the member (sum of successful transactions)
$stmt = $conn->prepare("SELECT SUM(Amount) as total_savings FROM saving WHERE Mid = ? AND Status = 'Success'");
$stmt->bind_param("s", $mid);
$stmt->execute();
$result = $stmt->get_result();
$total_savings = $result->fetch_assoc()['total_savings'] ?? 0.00;
$stmt->close();

define('ESEWA_SECRET', '8gBm/:&EnhH.1/q');
define('ESEWA_ENDPOINT', 'https://rc-epay.esewa.com.np/api/epay/main/v2/form');
define('SUCCESS_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/LoanApprovalPredction/Members/saving_success.php');
define('FAILURE_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/LoanApprovalPredction/Members/saving.php?failure=1');

function generateTransactionUUID() {
    return 'TXN' . time() . rand(1000, 9999);
}

$error = '';
$message = '';
$showPaymentForm = false;
$transaction_uuid = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['saving_amount'])) {
    $amount = trim($_POST['saving_amount']);

    if (!is_numeric($amount) || $amount <= 0) {
        $error = "Enter a valid amount.";
    } else {
        $transaction_uuid = generateTransactionUUID();
        $saving_date = date('Y-m-d H:i:s');

        // Start a transaction to ensure data consistency
        $conn->begin_transaction();

        try {
            // Insert into saving table with status 'pending'
            $stmt = $conn->prepare("INSERT INTO saving (Mid, Amount, SavingDate, TransactionUUID, Status) VALUES (?, ?, ?, ?, 'pending')");
            $stmt->bind_param("sdss", $mid, $amount, $saving_date, $transaction_uuid);
            $stmt->execute();
            $stmt->close();

            // Insert into balance table
            $stmt = $conn->prepare("INSERT INTO balance (Mid, TransactionUUID) VALUES (?, ?)");
            $stmt->bind_param("ss", $mid, $transaction_uuid);
            $stmt->execute();
            $stmt->close();

            // Commit the transaction
            $conn->commit();

            $_SESSION['esewa_data'] = [
                'amount' => $amount,
                'transaction_uuid' => $transaction_uuid
            ];

            // Generate signature for eSewa
            $product_code = 'EPAYTEST';
            $message = "total_amount={$amount},transaction_uuid={$transaction_uuid},product_code={$product_code}";
            $hmac = hash_hmac('sha256', $message, ESEWA_SECRET, true);
            $signature = base64_encode($hmac);

            // Auto-redirect to eSewa with POST data
            echo "<form id='esewa_redirect' action='" . ESEWA_ENDPOINT . "' method='POST'>
                    <input type='hidden' name='amount' value='$amount'/>
                    <input type='hidden' name='total_amount' value='$amount'/>
                    <input type='hidden' name='product_code' value='$product_code'/>
                    <input type='hidden' name='transaction_uuid' value='$transaction_uuid'/>
                    <input type='hidden' name='tax_amount' value='0'/>
                    <input type='hidden' name='product_service_charge' value='0'/>
                    <input type='hidden' name='product_delivery_charge' value='0'/>
                    <input type='hidden' name='success_url' value='" . SUCCESS_URL . "'/>
                    <input type='hidden' name='failure_url' value='" . FAILURE_URL . "'/>
                    <input type='hidden' name='signed_field_names' value='total_amount,transaction_uuid,product_code'/>
                    <input type='hidden' name='signature' value='$signature'/>
                  </form>
                  <script>document.getElementById('esewa_redirect').submit();</script>";
            exit();
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            $error = "DB Insert Error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Saving Form</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
    <?php include '../includes/navbar.php'; ?>
    <div class="flex items-center justify-center flex-grow">
        <div class="bg-white p-8 rounded-lg shadow-lg max-w-md w-full">
            <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">eSewa Saving Payment</h2>
            
            <!-- Display Total Savings and Last Transaction ID -->
            <div class="text-center mb-6">
                <p class="text-gray-700">Total Savings: NPR <?php echo number_format($total_savings, 2); ?></p>
                <?php if (!empty($transaction_uuid)): ?>
                    <p class="text-gray-700">Last Transaction ID: <?php echo htmlspecialchars($transaction_uuid); ?></p>
                <?php endif; ?>
            </div>
            
            <div class="text-center mb-6">
                <button id="toggleFormBtn" 
                        class="bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 transition duration-200">
                    Add Amount
                </button>
            </div>
            
            <?php if (!empty($error)): ?>
                <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6" role="alert">
                    <p><?php echo htmlspecialchars($error); ?></p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['failure'])): ?>
                <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 mb-6" role="alert">
                    <p>Payment was not completed. Please try again.</p>
                </div>
            <?php endif; ?>
            
            <form id="savingForm" method="POST" class="space-y-4 hidden">
                <div>
                    <label for="saving_amount" class="block text-sm font-medium text-gray-700">Enter Saving Amount</label>
                    <input type="number" name="saving_amount" id="saving_amount" min="1" step="0.01" required 
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                           placeholder="Enter amount">
                </div>
                <button type="submit" 
                        class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition duration-200">
                    Pay with eSewa
                </button>
            </form>
        </div>
    </div>
    <script>
        const toggleFormBtn = document.getElementById('toggleFormBtn');
        const savingForm = document.getElementById('savingForm');
        toggleFormBtn.addEventListener('click', () => {
            savingForm.classList.toggle('hidden');
            toggleFormBtn.textContent = savingForm.classList.contains('hidden') ? 'Add Amount' : 'Hide Form';
        });
    </script>
</body>
</html>