<?php
// Start session securely — must be at the very top
session_start([
    'cookie_httponly' => true,
    'cookie_secure' => isset($_SERVER['HTTPS']),
    'cookie_samesite' => 'Strict',
]);

// Set timezone for Nepal
date_default_timezone_set('Asia/Kathmandu');

// Protect page — redirect to login if not logged in
if (!isset($_SESSION['authenticated_user']) || $_SESSION['authenticated_user'] !== true || !isset($_SESSION['Mid'])) {
    $_SESSION['error'] = "Please log in to access the dashboard.";
    header("Location: /LoanApprovalPredction/Members/login.php");
    exit;
}



// Database connection
require_once '../includes/connection.php';

// Generate CSRF token if not set
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(24));
}

// Initialize variables
$mid = $_SESSION['Mid'];
$message = '';
$error = '';
$name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
$auto_submit = false;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Invalid CSRF token.";
        header("Location: /LoanApprovalPredction/Members/saving.php");
        exit;
    }

    // Validate inputs
    $loanamt = isset($_POST['la']) && is_numeric($_POST['la']) ? (int)$_POST['la'] : 0;
    $interest = isset($_POST['intrest']) && is_numeric($_POST['intrest']) ? (int)$_POST['intrest'] : 0;
    $lid = isset($_POST['lid']) && is_numeric($_POST['lid']) ? (int)$_POST['lid'] : null;
    $savingamt = isset($_POST['savingamt']) && is_numeric($_POST['savingamt']) ? (int)$_POST['savingamt'] : 0;

    // Validate saving amount
    if ($savingamt < 1000) {
        $_SESSION['error'] = "Saving amount must be at least Rs 1,000.";
        header("Location: /LoanApprovalPredction/Members/saving.php");
        exit;
    }

    // Validate Lid if provided
    if ($lid !== null) {
        $query_lid = "SELECT LID FROM loan WHERE LID = ? AND MID = ?";
        $stmt_lid = mysqli_prepare($conn, $query_lid);
        mysqli_stmt_bind_param($stmt_lid, "ii", $lid, $mid);
        mysqli_stmt_execute($stmt_lid);
        $result_lid = mysqli_stmt_get_result($stmt_lid);
        if (mysqli_num_rows($result_lid) === 0) {
            $lid = null; // Invalid Lid, set to null
        }
        mysqli_stmt_close($stmt_lid);
    }

    $total = $interest + $savingamt + $loanamt;
    $invoice = time();
    $date = date('Y-m-d');

    // Check last saving date
    $query = "SELECT saving_date FROM saving WHERE Mid = ? ORDER BY saving_id DESC LIMIT 1";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "i", $mid);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        if ((time() - strtotime($row['saving_date'])) < 60 * 60 * 24 * 30) {
            $_SESSION['error'] = "You cannot save your balance now.";
            header("Location: /LoanApprovalPredction/Members/saving.php");
            exit;
        }
    }
    mysqli_stmt_close($stmt);

    // Insert new saving record
    $deposit_query = "INSERT INTO saving (MID, savingamt, intrest, LID, saving_date, invoice, status, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt_deposit = mysqli_prepare($conn, $deposit_query);
    $status = 'pending';
    if ($lid === null) {
        $null_lid = null;
        mysqli_stmt_bind_param($stmt_deposit, "iiiisisi", $mid, $savingamt, $interest, $null_lid, $date, $invoice, $status, $total);
    } else {
        mysqli_stmt_bind_param($stmt_deposit, "iiiiisii", $mid, $savingamt, $interest, $lid, $date, $invoice, $status, $total);
    }

    if (mysqli_stmt_execute($stmt_deposit)) {
        // Update totalbalance
        $sql_total = "SELECT COUNT(*) AS count FROM totalbalance";
        $result_total = mysqli_query($conn, $sql_total);
        $data = mysqli_fetch_assoc($result_total)['count'];

        $sql_save = "SELECT saving_id FROM saving WHERE MID = ? ORDER BY saving_id DESC LIMIT 1";
        $stmt_save = mysqli_prepare($conn, $sql_save);
        mysqli_stmt_bind_param($stmt_save, "i", $mid);
        mysqli_stmt_execute($stmt_save);
        $result_save = mysqli_stmt_get_result($stmt_save);
        $sid = mysqli_fetch_assoc($result_save)['saving_id'];
        mysqli_stmt_close($stmt_save);

        if ($data == 0) {
            $sqli1 = "INSERT INTO totalbalance (ddate, amount) VALUES (?, 0)";
            $stmt_tb = mysqli_prepare($conn, $sqli1);
            mysqli_stmt_bind_param($stmt_tb, "i", $sid);
            mysqli_stmt_execute($stmt_tb);
            mysqli_stmt_close($stmt_tb);
        } else {
            $sqli1 = "UPDATE totalbalance SET ddate = ?, amount = amount + ? WHERE TB_id = (SELECT MAX(TB_id) FROM totalbalance)";
            $stmt_tb = mysqli_prepare($conn, $sqli1);
            mysqli_stmt_bind_param($stmt_tb, "ii", $sid, $total);
            mysqli_stmt_execute($stmt_tb);
            mysqli_stmt_close($stmt_tb);
        }

        // Set flag to auto-submit to eSewa
        $auto_submit = true;
        $message = "Proceeding to eSewa payment for Rs " . number_format($total, 2);
    } else {
        $_SESSION['error'] = "Error saving balance: " . mysqli_error($conn);
        header("Location: /LoanApprovalPredction/Members/saving.php");
        exit;
    }
    mysqli_stmt_close($stmt_deposit);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="icon" href="../images/Icon.png" type="image/png">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .btn-primary {
            transition: background-color 0.3s ease, transform 0.2s ease;
        }
        .btn-primary:hover {
            background-color: #1e40af;
            transform: translateY(-2px);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-gray-100 min-h-screen font-sans">
    <!-- Header -->
    <header class="bg-white shadow">
        <?php include '../includes/navbar.php'; ?>
    </header>

    <!-- Message Display -->
    <div id="message" class="fixed top-4 left-1/2 transform -translate-x-1/2 hidden z-50 max-w-md">
        <?php if ($message): ?>
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded-lg flex items-center fade-in">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
                <p><?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
        <?php elseif ($error): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg flex items-center fade-in">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <p><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Main Content -->
    <div class="container mx-auto p-8">
        <!-- Saving Amount Form -->
        <div class="flex justify-center">
            <form id="paymentForm" action="https://uat.esewa.com.np/epay/main" method="POST" class="bg-white p-6 rounded-xl shadow-2xl fade-in w-full max-w-md" onsubmit="return validateForm()">
                <h2 class="text-2xl font-bold mb-4 text-center">Enter Saving Amount</h2>
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="intrest" value="<?php echo htmlspecialchars($_POST['intrest'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="la" value="<?php echo htmlspecialchars($_POST['la'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="lid" value="<?php echo htmlspecialchars($_POST['lid'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="submit" value="1">
                <?php if ($auto_submit): ?>
                    <input value="<?php echo htmlspecialchars($total, ENT_QUOTES, 'UTF-8'); ?>" name="tAmt" type="hidden">
                    <input value="<?php echo htmlspecialchars($total, ENT_QUOTES, 'UTF-8'); ?>" name="amt" type="hidden">
                    <input value="0" name="txAmt" type="hidden">
                    <input value="0" name="psc" type="hidden">
                    <input value="0" name="pdc" type="hidden">
                    <input value="epay_payment" name="scd" type="hidden">
                    <input value="<?php echo htmlspecialchars($invoice, ENT_QUOTES, 'UTF-8'); ?>" name="pid" type="hidden">
                    <input value="http://localhost/LoanApprovalPredction/Members/esewa_payment_success.php" name="su" type="hidden">
                    <input value="http://localhost/LoanApprovalPredction/Members/esewa_payment_failed.php" name="fu" type="hidden">
                <?php endif; ?>
                <div class="mb-4">
                    <label for="savingamt" class="block text-sm font-medium text-gray-700">Saving Amount (Rs)</label>
                    <input type="number" id="savingamt" name="savingamt" min="1000" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500" placeholder="Enter amount (min Rs 1,000)">
                </div>
                <input type="submit" value="Proceed to Payment" class="btn-primary bg-blue-500 text-white rounded uppercase border border-black w-full py-2 hover:bg-blue-600">
            </form>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const messageElement = document.getElementById("message");
            if (messageElement.children.length > 0) {
                messageElement.classList.remove("hidden");
                setTimeout(() => {
                    messageElement.classList.add("hidden");
                }, 5000);
            }

            <?php if ($auto_submit): ?>
                // Auto-submit the form to eSewa
                document.getElementById("paymentForm").submit();
            <?php endif; ?>
        });

        function validateForm() {
            const savingAmt = document.getElementById('savingamt').value;
            if (savingAmt < 1000) {
                alert("Saving amount must be at least Rs 1,000.");
                return false;
            }
            return confirm("Are you sure you want to proceed with a saving of Rs " + savingAmt + "?");
        }
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>