<?php
session_start();


include("../config/theconfig.php");
include("header.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit(); // Always exit after a header redirect
}

// Handle Delete Operation
if (isset($_POST["delete"])) {
    // Use a prepared statement to prevent SQL injection
    $stmt = mysqli_prepare($conn, "DELETE FROM branch WHERE ifsccode=?");
    mysqli_stmt_bind_param($stmt, "s", $_POST['emp']);
    
    if (mysqli_stmt_execute($stmt)) {
        if (mysqli_stmt_affected_rows($stmt) == 1) {
            echo "<script>swal('Successful!', 'Branch Has Been Deleted!', 'success')</script>";
        } else {
            echo "<script>swal('Failed!', 'Failed to delete branch or branch not found!', 'error')</script>";
        }
    } else {
        echo "<script>swal('Error!', 'Error deleting record: " . mysqli_error($conn) . "', 'error')</script>";
    }
    mysqli_stmt_close($stmt);
}

// Handle Create Branch Operation
if (isset($_POST["button"])) {
    // Check if the branch already exists using a prepared statement
    $stmt_check = mysqli_prepare($conn, "SELECT ifsccode FROM branch WHERE ifsccode=?");
    mysqli_stmt_bind_param($stmt_check, "s", $_POST['ifsc']);
    mysqli_stmt_execute($stmt_check);
    mysqli_stmt_store_result($stmt_check);
    
    if (mysqli_stmt_num_rows($stmt_check) > 0) {
        echo "<script>swal('Error!', 'This Branch Has Already Been Created!', 'error')</script>";
    } else {
        // Insert the new branch record using a prepared statement
        $stmt_insert = mysqli_prepare($conn, "INSERT INTO branch (ifsccode, branchname, country, city, state, branchaddress) VALUES (?, ?, ?, ?, ?, ?)");
        mysqli_stmt_bind_param($stmt_insert, "ssssss", $_POST['ifsc'], $_POST['branch'], $_POST['country'], $_POST['city'], $_POST['state'], $_POST['address']);
        
        if (mysqli_stmt_execute($stmt_insert)) {
            echo "<script>swal('Success!', 'Bank Branch Created Successfully!', 'success')</script>";
        } else {
            echo "<script>swal('Error!', 'Error creating record: " . mysqli_error($conn) . "', 'error')</script>";
        }
        mysqli_stmt_close($stmt_insert);
    }
    mysqli_stmt_close($stmt_check);
}

// Fetch all branches
$stmt_loan = mysqli_prepare($conn, "SELECT * FROM branch");
mysqli_stmt_execute($stmt_loan);
$result_loan = mysqli_stmt_get_result($stmt_loan);
?>
<div class="dt-content-wrapper">

    <div class="dt-content">

        <div class="dt-page__header">
            <h1 class="dt-page__title">Manage Bank Branches</h1>
        </div>
        <div class="row">
            
            <div class="col-xl-12">

                <div class="dt-entry__header">

                    <div class="dt-entry__heading">
                        <h3 class="dt-entry__title">All Branches</h3>
                    </div>
                    </div>
                <div class="dt-card">

                    <div class="dt-card__body">
                        <a href="branch.php"><button class='btn btn-secondary'>Create New Branch </button></a>
                        <br>
                        <div class="table-responsive">
                            <table id="data-table" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>Branch Name</th>
                                        <th>Branch Code</th>
                                        <th>Country</th>
                                        <th>State</th>
                                        <th>Address</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    while ($arrvar = mysqli_fetch_assoc($result_loan)) {
                                        echo "<tr>";
                                        echo "<td>" . htmlspecialchars($arrvar['branchname']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['ifsccode']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['country']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['state']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['branchaddress']) . "</td>";
                                        echo "<td>
                                                <form method='post' action='managebranch.php' onsubmit=\"return confirm('Are you sure you want to delete this branch?');\">
                                                    <input type='hidden' value='" . htmlspecialchars($arrvar['ifsccode']) . "' name='emp'>
                                                    <input type='submit' class='btn btn-secondary' name='delete' value='Delete' />
                                                </form>
                                              </td>";
                                        echo "</tr>";
                                    }
                                    ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th>Branch Name</th>
                                        <th>Branch Code</th>
                                        <th>Country</th>
                                        <th>State</th>
                                        <th>Address</th>
                                        <th>Action</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php 
mysqli_stmt_close($stmt_loan); // Close the statement after fetching
include 'footer.php';
// The database connection should be closed at the end of the script.
?>
    
<script src="../assets/node_modules/datatables.net/js/jquery.dataTables.js"></script>
<script src="../assets/node_modules/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
<script src="../assets/js/custom/data-table.js"></script>