<?php
session_start();
// Enable error reporting for development. In a production environment, you might change this.


// This file is assumed to contain the mysqli connection setup, e.g., $con = mysqli_connect(...)
include("../config/theconfig.php");
include("header.php");

// Check if the connection variable exists
if (!isset($con) || !$con) {
    die("Database connection failed. Check your config file.");
}

// Check for login session
if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit();
}

$dts = date("l jS \of F Y");

// Use prepared statement for the last login update
$stmt = mysqli_prepare($con, "UPDATE customers SET lastlogin=? WHERE customerid=?");
mysqli_stmt_bind_param($stmt, 'ss', $dts, $_SESSION['customerid']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

// Handle deposit form submission
if (isset($_POST['deposit'])) {
    // Sanitize and validate input
    $now = (float)$_POST['mone'];
    $dt = date("Y-m-d H:i:s"); // Or whatever your $dt variable is
    $lid = isset($_POST['lid']) ? $_POST['lid'] : null;
    $amt = isset($_POST['amt']) ? $_POST['amt'] : null;

    // Use prepared statements for transactions
    $stmt1 = mysqli_prepare($con, "UPDATE accounts SET accountbalance = accountbalance + ? WHERE customerid = ?");
    mysqli_stmt_bind_param($stmt1, 'ds', $now, $_SESSION['customerid']);
    mysqli_stmt_execute($stmt1);
    mysqli_stmt_close($stmt1);

    // This query seems unrelated to 'deposit' but is in the original code. Updated for security.
    $stmt2 = mysqli_prepare($con, "INSERT INTO loanpayment (customerid, loanid, paidamt, date) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($stmt2, 'ssss', $_SESSION['customerid'], $lid, $amt, $dt);
    mysqli_stmt_execute($stmt2);
    mysqli_stmt_close($stmt2);

    header('Location: dashboard.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Transfer History</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="" name="description" />
    <meta content="" name="author" />
    <link rel="shortcut icon" href="assets/images/favicon.ico">
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <script src="assets/libs2/custom/sweetalert.min.js"></script>
    <style>
        .swal-text {
            font-size: 13px;
        }
    </style>
</head>

<body data-sidebar="colored">
<div id="layout-wrapper">

    <div class="main-content">
        <?php
        // Fetch account and fixed deposit data using prepared statements
        $stmt_accounts = mysqli_prepare($con, "SELECT * FROM accounts WHERE customerid=?");
        mysqli_stmt_bind_param($stmt_accounts, 's', $_SESSION['customerid']);
        mysqli_stmt_execute($stmt_accounts);
        $result_accounts = mysqli_stmt_get_result($stmt_accounts);
        $rowrec = mysqli_fetch_assoc($result_accounts);
        mysqli_stmt_close($stmt_accounts);

        $stmt_fixed_deposit = mysqli_prepare($con, "SELECT * FROM fixed_deposit WHERE customerid=?");
        mysqli_stmt_bind_param($stmt_fixed_deposit, 's', $_SESSION['customerid']);
        mysqli_stmt_execute($stmt_fixed_deposit);
        $result_fixed_deposit = mysqli_stmt_get_result($stmt_fixed_deposit);
        $rowrec2 = mysqli_fetch_assoc($result_fixed_deposit);
        mysqli_stmt_close($stmt_fixed_deposit);

        // Handle fixed deposit form submission
        if (isset($_POST['fixed'])) {
            $act = htmlspecialchars($_POST['act']);
            $amount = htmlspecialchars($_POST['amount']);
            $duration = htmlspecialchars($_POST['duration']);
            $status = 1;

            $stmt_fixed = mysqli_prepare($con, "INSERT fixed_deposit (customerid, accno, amount, duration, status) VALUES (?, ?, ?, ?, ?)");
            mysqli_stmt_bind_param($stmt_fixed, 'ssiss', $_SESSION['customerid'], $act, $amount, $duration, $status);
            $query_success = mysqli_stmt_execute($stmt_fixed);
            mysqli_stmt_close($stmt_fixed);

            if ($query_success) {
                echo "<script>
                    swal('Successful!', 'Your Fixed Deposit Account Has Been Created. Your Fixed Deposit Account Number Is " . htmlspecialchars($act) . "', 'success');
                </script>";
            } else {
                echo "<script>
                    swal('Error!', 'An error occurred. Please try again.', 'error');
                </script>";
            }
        }
        ?>

        <div class="page-content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                            <h4 class="mb-sm-0 font-size-18">Transfer History</h4>
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="javascript: void(0);">Dashboards</a></li>
                                    <li class="breadcrumb-item active">Transfer History</li>
                                </ol>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title mb-4">Latest Transaction</h4>

                                <div id="datatable_wrapper" class="dataTables_wrapper dt-bootstrap4 no-footer">
                                    <style> @media (min-width:900px){.table-responsive{overflow:hidden !Important;}}</style>
                                    <div class="">
                                        <table id="datatable" class="table table-bordered dt-responsive nowrap w-100 dataTable no-footer dtr-inline" role="grid" aria-describedby="datatable_info" style="width: 1013px;">
                                            <thead class="table-light">
                                            <tr>
                                                <th class="align-middle">Transaction ID</th>
                                                <th class="align-middle">Transaction Date</th>
                                                <th class="align-middle">Account Number</th>
                                                <th class="align-middle">Receivers's Bank</th>
                                                <th class="align-middle">Amount</th>
                                                <th class="align-middle">Status</th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            <?php
                                            // Use a prepared statement to fetch transfer history
                                            $stmt_transfers = mysqli_prepare($con, "SELECT * FROM transfers WHERE sender=?");
                                            mysqli_stmt_bind_param($stmt_transfers, 's', $_SESSION['customerid']);
                                            mysqli_stmt_execute($stmt_transfers);
                                            $rectrans = mysqli_stmt_get_result($stmt_transfers);
                                            while ($recs = mysqli_fetch_assoc($rectrans)) {
                                                $transid = htmlspecialchars($recs['id']);
                                                $transdate = htmlspecialchars($recs['date']);
                                                $receiveid = htmlspecialchars($recs['receiver']);
                                                $receivebank = htmlspecialchars($recs['bank']);
                                                $amount = htmlspecialchars($recs['amount']);
                                                $status = htmlspecialchars($recs['status']);
                                                $blnce = number_format($recs['amount'], 2);
                                                ?>
                                                <tr>
                                                    <td>TRANS<?php echo $transid; ?></td>
                                                    <td><?php echo $transdate; ?></td>
                                                    <td><?php echo $receiveid; ?></td>
                                                    <td><?php echo $receivebank; ?></td>
                                                    <td><?php echo $cur . ' ' . $blnce; ?></td>
                                                    <td>
                                                        <span class="badge badge-pill badge-soft-danger font-size-11"><?php if ($status == '0') echo "Pending"; ?></span>
                                                        <span class="badge badge-pill badge-soft-success font-size-11"><?php if ($status == '1') echo "Successful"; ?></span>
                                                    </td>
                                                </tr>
                                                <?php
                                            }
                                            mysqli_stmt_close($stmt_transfers);
                                            ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="text-right mt-3">
                                        <input type="button" class="btn btn-primary w-xs waves-effect waves-light" value="Print Transaction Detail" onClick="window.print()">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                </div>
            </div>
        <?php include 'footer.php'; ?>
    </div>
    </div>
<div class="rightbar-overlay"></div>
<script src="assets/libs/jquery/jquery.min.js"></script>
<script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/libs/metismenu/metisMenu.min.js"></script>
<script src="assets/libs/simplebar/simplebar.min.js"></script>
<script src="assets/libs/node-waves/waves.min.js"></script>
<script src="assets/libs/apexcharts/apexcharts.min.js"></script>
<script src="assets/js/pages/dashboard.init.js"></script>
<script src="assets/js/app.js"></script>

<script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="assets/libs/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="assets/libs/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
<script src="assets/libs/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
<script src="assets/libs/jszip/jszip.min.js"></script>
<script src="assets/libs/pdfmake/build/pdfmake.min.js"></script>
<script src="assets/libs/pdfmake/build/vfs_fonts.js"></script>
<script src="assets/libs/datatables.net-buttons/js/buttons.html5.min.js"></script>
<script src="assets/libs/datatables.net-buttons/js/buttons.print.min.js"></script>
<script src="assets/libs/datatables.net-buttons/js/buttons.colVis.min.js"></script>

<script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
<script src="assets/libs/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>

<script src="assets/js/pages/datatables.init.js"></script>

<?php mysqli_close($con); ?>
</body>
</html>