<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include("check_installation.php");
include("fetch_settings.php");

if ($con->connect_error) {
    // Log the error for debugging on the server side
    error_log("Connection failed: " . $con->connect_error);
    // Display a generic error to the user
    die("Database connection failed. Please try again later.");
}

// Redirect if not logged in
if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

if (isset($_POST["button"])) {
    // Use proper variable names and validation
    $account_type = $_POST['acct'];
    $prefix = $_POST['code'];
    $min_balance = $_POST['min'];
    $interest = $_POST['int'];

    // Convert inputs to their intended types and validate
    $min_balance = filter_var($min_balance, FILTER_VALIDATE_FLOAT);
    $interest = filter_var($interest, FILTER_VALIDATE_FLOAT);
    
    // Check if validation failed for numbers
    if ($min_balance === false || $interest === false) {
        $_SESSION['message'] = [
            'type' => 'error',
            'text' => 'Invalid minimum balance or interest rate. Please enter a valid number.'
        ];
        header("Location: create_account.php"); // Redirect to self
        exit;
    }

    // Use a prepared statement to prevent SQL injection
    $sql = "INSERT INTO accountmaster (accounttype, prefix, minbalance, interest) VALUES (?, ?, ?, ?)";
    
    if ($stmt = $con->prepare($sql)) {
        // Bind parameters: s = string, d = double (for float)
        $stmt->bind_param("ssdd", $account_type, $prefix, $min_balance, $interest);
        
        if ($stmt->execute()) {
            $_SESSION['message'] = [
                'type' => 'success',
                'text' => 'New Account Type Created Successfully!'
            ];
        } else {
            $_SESSION['message'] = [
                'type' => 'error',
                'text' => "Error: " . $stmt->error
            ];
        }
        $stmt->close();
    } else {
        $_SESSION['message'] = [
            'type' => 'error',
            'text' => 'Database error: Unable to prepare statement.'
        ];
    }
    
    // Redirect to the same page to show the SweetAlert and prevent form resubmission
    header("Location: accounttype.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Create New Bank Account Type</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="author">
    <meta name="description" content="">
	<link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/choices/css/choices.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>

<body>
<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">Create New Bank Account Type</h1>
                    </div>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">New Bank Account Type</h5>
                </div>

                <div class="card-body">
                    <?php if (isset($_SESSION['message'])): 
                        $message = $_SESSION['message'];
                        unset($_SESSION['message']);
                    ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    icon: '<?= $message['type']; ?>',
                                    title: '<?= $message['type'] === 'success' ? 'Success!' : 'Error!'; ?>',
                                    html: '<?= $message['text']; ?>',
                                    confirmButtonText: 'OK'
                                });
                            });
                        </script>
                    <?php endif; ?>
                    
                    <form method="post" action="">
                        <div class="row">
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label>Account Name</label>
                                    <input required name="acct" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label>Account Code</label>
                                    <input required name="code" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label>Account Minimum Balance</label>
                                    <input required name="min" type="number" step="0.01" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label>Savings Interest (%)</label>
                                    <input required name="int" type="number" step="0.01" class="form-control">
                                </div>
                            </div>
                        </div>
                        
                        <div class="pt-4">
                            <button type="submit" name="button" class="btn btn-primary">Create Account Type</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/vendor/choices/js/choices.min.js"></script>
<script src="assets/js/functions.js"></script>
</body>
</html>