<?php
ob_start();
session_start();


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

// Check for admin session, assuming theconfig.php provides the $conn variable
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 accountmaster WHERE id=?");
    mysqli_stmt_bind_param($stmt, "i", $_POST['id']);
    
    if (mysqli_stmt_execute($stmt)) {
        if (mysqli_stmt_affected_rows($stmt) == 1) {
            echo "<script>swal('Successful!', 'Account Type Has Been Deleted!', 'success')</script>";
        } else {
            echo "<script>swal('Failed!', 'Failed to delete account or account not found!', 'error')</script>";
        }
    } else {
        echo "<script>swal('Error!', 'Error deleting record: " . mysqli_error($conn) . "', 'error')</script>";
    }
    mysqli_stmt_close($stmt);
}

// Handle Create Account Type Operation (The original code had a bug here, referencing "branch" tables. I've corrected it to be logical for "accountmaster")
if (isset($_POST["button"])) {
    // Use a prepared statement to prevent SQL injection
    $stmt_check = mysqli_prepare($conn, "SELECT id FROM accountmaster WHERE accounttype=?");
    mysqli_stmt_bind_param($stmt_check, "s", $_POST['accounttype']);
    mysqli_stmt_execute($stmt_check);
    mysqli_stmt_store_result($stmt_check);
    
    if (mysqli_stmt_num_rows($stmt_check) > 0) {
        echo "<script>swal('Error!', 'This Account Type has already been created!', 'error')</script>";
    } else {
        $stmt_insert = mysqli_prepare($conn, "INSERT INTO accountmaster (accounttype, prefix, minbalance, interest) VALUES (?, ?, ?, ?)");
        mysqli_stmt_bind_param($stmt_insert, "ssdi", $_POST['accounttype'], $_POST['prefix'], $_POST['minbalance'], $_POST['interest']);
        
        if (mysqli_stmt_execute($stmt_insert)) {
            echo "<script>swal('Success!', 'Account Type 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 account types
$stmt_loan = mysqli_prepare($conn, "SELECT * FROM accountmaster");
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 Account Type</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 Accounts</h3>
                    </div>
                    </div>
                <div class="dt-card">

                    <div class="dt-card__body">
                        
                        <a href="accounttype.php"><button class='btn btn-secondary'>Create New Account Type </button></a>
                        <br>
                        
                        <div class="table-responsive">

                            <table id="data-table" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>Account Name</th>
                                        <th>Account Code</th>
                                        <th>Minimum Balance</th>
                                        <th>Interest</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    while ($arrvar = mysqli_fetch_assoc($result_loan)) {
                                        echo "<tr>";
                                        echo "<td>" . htmlspecialchars($arrvar['accounttype']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['prefix']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['minbalance']) . "</td>";
                                        echo "<td>" . htmlspecialchars($arrvar['interest']) . "</td>";
                                        echo "<td>
                                                <form method='post' action='manageaccount.php' onsubmit=\"return confirm('Are you sure you want to delete this account type?');\">
                                                    <input type='hidden' value='" . htmlspecialchars($arrvar['id']) . "' name='id'>
                                                    <input type='submit' class='btn btn-secondary' name='delete' value='Delete' />
                                                </form>
                                              </td>";
                                        echo "</tr>";
                                    }
                                    ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th>Account Name</th>
                                        <th>Account Code</th>
                                        <th>Minimum Balance</th>
                                        <th>Interest</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 in the footer or at the very 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>