<?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) {
    die("Connection failed: " . $con->connect_error);
}

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

if (isset($_POST["button"])) {
    $ifsc = $_POST['ifsc'];
    $branchname = $_POST['branch'];
    $country = $_POST['country'];
    $city = $_POST['city'];
    $state = $_POST['state'];
    $address = $_POST['address'];

    // Step 1: Check if the IFSC code already exists using a prepared statement
    $sql_check = "SELECT ifsccode FROM branch WHERE ifsccode = ?";
    if ($stmt_check = $con->prepare($sql_check)) {
        $stmt_check->bind_param("s", $ifsc);
        $stmt_check->execute();
        $stmt_check->store_result();

        if ($stmt_check->num_rows > 0) {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Error! This Branch Has Already Been Created!'];
        } else {
            // Step 2: Insert the new branch record using a prepared statement
            $sql_insert = "INSERT INTO branch (ifsccode, branchname, country, city, state, branchaddress) VALUES (?, ?, ?, ?, ?, ?)";
            if ($stmt_insert = $con->prepare($sql_insert)) {
                $stmt_insert->bind_param("ssssss", $ifsc, $branchname, $country, $city, $state, $address);
                
                if ($stmt_insert->execute()) {
                    $_SESSION['message'] = ['type' => 'success', 'text' => 'Bank Branch Created Successfully!'];
                } else {
                    $_SESSION['message'] = ['type' => 'error', 'text' => 'Error: ' . $stmt_insert->error];
                }
                $stmt_insert->close();
            } else {
                $_SESSION['message'] = ['type' => 'error', 'text' => 'Database error: Unable to prepare insert statement.'];
            }
        }
        $stmt_check->close();
    } else {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Database error: Unable to prepare check statement.'];
    }

    // Redirect to self to prevent form resubmission and display the SweetAlert
    header("Location: createbranch.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Create New Bank Branch</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <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">New Branch</h1>
                    </div>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">Create New Bank Branch</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 class="form-label">Branch Name</label>
                                    <input required name="branch" id="branchname" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Branch Country</label>
                                    <select id="country" name="country" class="form-control" required>
                                        <option value="">Loading...</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Enter Branch State</label>
                                    <select id="state" name="state" class="form-control" required>
                                        <option value="">Select country first</option>
                                    </select>
								</div>	
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Enter Branch City</label>
                                    <select id="city" name="city" class="form-control" required>
                                        <option value="">Select state first</option>
                                    </select>
									</div>
                                
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Branch IFSC Code</label>
                                    <input required name="ifsc" id="ifsc" class="form-control">
                                </div>
                            </div>
                            
                            <div class="col-sm-6 mb-3">
                                <div class="form-group">
                                    <label class="form-label">Branch Address</label>
                                    <input required type="text" name="address" id="address" class="form-control">
                                </div>
                            </div>
                        </div>
                        
                        <div class="pt-4">
                            <button type="submit" name="button" class="btn btn-primary">Create Branch</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>


<script>
document.addEventListener("DOMContentLoaded", function () {
    let countrySelect = document.getElementById("country");
    let stateSelect   = document.getElementById("state");
    let citySelect    = document.getElementById("city");

    // Load countries
    fetch("https://countriesnow.space/api/v0.1/countries/positions")
        .then(res => res.json())
        .then(data => {
            countrySelect.innerHTML = "<option value=''>Select Country</option>";
            data.data.forEach(c => {
                countrySelect.innerHTML += `<option value="${c.name}">${c.name}</option>`;
            });
        });

    // When country is selected → load states
    countrySelect.addEventListener("change", function () {
        let country = this.value;
        stateSelect.innerHTML = "<option value=''>Loading...</option>";
        citySelect.innerHTML = "<option value=''>Select state first</option>";

        fetch("https://countriesnow.space/api/v0.1/countries/states", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ country: country })
        })
        .then(res => res.json())
        .then(data => {
            stateSelect.innerHTML = "<option value=''>Select State</option>";
            if (data.data && data.data.states) {
                data.data.states.forEach(s => {
                    stateSelect.innerHTML += `<option value="${s.name}">${s.name}</option>`;
                });
            }
        });
    });

    // When state is selected → load cities
    stateSelect.addEventListener("change", function () {
        let state = this.value;
        let country = countrySelect.value;
        citySelect.innerHTML = "<option value=''>Loading...</option>";

        fetch("https://countriesnow.space/api/v0.1/countries/state/cities", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ country: country, state: state })
        })
        .then(res => res.json())
        .then(data => {
            citySelect.innerHTML = "<option value=''>Select City</option>";
            if (data.data) {
                data.data.forEach(city => {
                    citySelect.innerHTML += `<option value="${city}">${city}</option>`;
                });
            }
        });
    });
});
</script>

</body>
</html>