<?php
session_start();
error_reporting(0);
include("../config/theconfig.php");

include("header.php");

if (!($_SESSION["adminid"])) {
    header("Location: login.php");
    exit();
}

// Assume $conn is defined in '../config/theconfig.php'
if (!isset($conn)) {
    die("Connection variable \$conn is not set. Please check theconfig.php.");
}

$dt = date("Y-m-d h:i:s");

// Sanitize input to prevent SQL Injection
$custid = isset($_GET['custid']) ? mysqli_real_escape_string($conn, $_GET['custid']) : '';

$results = mysqli_query($conn, "SELECT * FROM customers WHERE customerid='$custid'");
$custid_orig = $_GET['custid'];

while ($arrow = mysqli_fetch_array($results)) {
    $custname = $arrow['firstname'] . " " . $arrow['lastname'];
    $ifsccode = $arrow['ifsccode'];
    $loginid = $arrow['loginid'];
    $accstatus = $arrow['accstatus'];
    $city = $arrow['city'];
    $state = $arrow['state'];
    $country = $arrow['country'];
    $accopendate = $arrow['accopendate'];
    $lastlogin = $arrow['lastlogin'];
}

$resultsd = mysqli_query($conn, "SELECT * FROM accounts WHERE customerid='$custid'");
$num_rows = mysqli_num_rows($resultsd);
?>
<div class="dt-content-wrapper">
    <div class="dt-content">
        <div class="dt-page__header">
            <h1 class="dt-page__title">Debit Customer</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">Debit Account</h3>
                    </div>
                    </div>
                <div class="dt-card">
                    <div class="dt-card__body">
                        <div class="table-responsive">
                            <blockquote>
<?php
if (isset($_REQUEST['debit'])) {
    // Sanitize POST data
    $amount = mysqli_real_escape_string($conn, $_REQUEST['amount']);
    $custid_req = mysqli_real_escape_string($conn, $_REQUEST['custid']);
    $paymentdate = mysqli_real_escape_string($conn, $_REQUEST['paymentdate']);

    // Check if the debit amount is available
    $check_balance_query = "SELECT accountbalance FROM accounts WHERE customerid = '$custid_req'";
    $balance_result = mysqli_query($conn, $check_balance_query);
    $balance_row = mysqli_fetch_assoc($balance_result);
    $current_balance = $balance_row['accountbalance'];

    if ($current_balance >= $amount) {
        // Insert into transactions
        $insert_sql = "INSERT INTO transactions (cashier, type, paymentdate, charged, amount, paymentstat) VALUES ('$_SESSION[adminid]', 'Debit', '$paymentdate', '$custid_req', '$amount', 'active')";
        if (mysqli_query($conn, $insert_sql)) {
            // Update account balance
            $update_sql = "UPDATE accounts SET accountbalance = accountbalance - '$amount' WHERE customerid = '$custid_req'";
            if (mysqli_query($conn, $update_sql)) {
                echo "<script>swal('Successful!', 'Account Successfully Debited!', 'success');</script>";
            } else {
                echo "<script>swal('Error!', 'Failed to update account balance: " . mysqli_error($conn) . "', 'error');</script>";
            }
        } else {
            echo "<script>swal('Error!', 'Failed to record transaction: " . mysqli_error($conn) . "', 'error');</script>";
        }
    } else {
        echo "<script>swal('Insufficient Funds!', 'The account balance is not enough to cover this debit.', 'error');</script>";
    }
}
?>
                            </blockquote>
                            <table id="data-table" class="table table-striped table-bordered table-hover">
                                <tr>
                                    <th colspan="5" scope="col"><strong>CUSTOMER ACCOUNTS</strong></th>
                                </tr>
                                <tr>
                                    <th width="100" scope="col"><strong>ACCOUNT NO</strong></th>
                                    <th width="75" scope="col"><strong>STATUS</strong></th>
                                    <th width="90" scope="col"><strong>OPEN DATE</strong></th>
                                    <th width="90" scope="col"><strong>ACCOUNT TYPE</strong></th>
                                    <th width="85" scope="col"><strong>BALANCE</strong></th>
                                </tr>
                                <?php
                                while ($arrow = mysqli_fetch_array($resultsd)) {
                                ?>
                                    <tr>
                                        <td>&nbsp;<?php echo htmlspecialchars($arrow['accno']); ?></td>
                                        <td>&nbsp;<?php echo htmlspecialchars($arrow['accstatus']); ?></td>
                                        <td>&nbsp;<?php echo htmlspecialchars($arrow['accopendate']); ?></td>
                                        <td>&nbsp;<?php echo htmlspecialchars($arrow['accounttype']); ?></td>
                                        <td>&nbsp;<?php echo " $cur " . htmlspecialchars($arrow['accountbalance']); ?></td>
                                    </tr>
                                <?php
                                }
                                ?>
                            </table>
                            <p>&nbsp;</p>
                            <tr>
                                <td colspan="2">
                                    <div align="right">
                                        <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#myModal">Debit Account</button>
                                    </div>
                                </td>
                            </tr>
                        </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Debit User</h4>
            </div>
            <div class="modal-body">
                <form method="post" action="">
                    <div class="form-group">
                        <input type="hidden" value="<?php echo htmlspecialchars($custid_orig); ?>" name="custid">
                        <label>Enter Amount To Debit</label>
                        <input type="number" name="amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Debit Transaction Date</label>
                        <input type="datetime-local" name="paymentdate" class="form-control" required>
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                <input name="debit" type="submit" value="Debit" class="btn btn-secondary">
            </div>
            </form>
        </div>
    </div>
</div>

<?php include 'footer.php' ?>
<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>