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

// Redirect if the user is not logged in
if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit();
}

// Check for the database connection
if (!isset($conn) || !$conn) {
    die("Database connection failed. Please check the 'theconfig.php' file.");
}

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

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

// Fetch data using prepared statements
$results_accounts = mysqli_prepare($conn, "SELECT * FROM accounts WHERE customerid=?");
mysqli_stmt_bind_param($results_accounts, "s", $_SESSION['customerid']);
mysqli_stmt_execute($results_accounts);
$rowrec = mysqli_fetch_assoc(mysqli_stmt_get_result($results_accounts));
mysqli_stmt_close($results_accounts);

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

$results_customers = mysqli_prepare($conn, "SELECT * FROM customers WHERE customerid=?");
mysqli_stmt_bind_param($results_customers, "s", $_SESSION['customerid']);
mysqli_stmt_execute($results_customers);
$rowrec1 = mysqli_fetch_assoc(mysqli_stmt_get_result($results_customers));
mysqli_stmt_close($results_customers);

// Handle deposit action securely
if (isset($_POST['deposit'])) {
    $now = $_POST['mone'];
    $lid = $_POST['lid'];
    $amt = $_POST['amt'];
    $dt = date("Y-m-d");

    // Update account balance
    $stmt_deposit = mysqli_prepare($conn, "UPDATE accounts SET accountbalance = accountbalance + ? WHERE customerid=?");
    mysqli_stmt_bind_param($stmt_deposit, "ds", $now, $_SESSION['customerid']);
    mysqli_stmt_execute($stmt_deposit);
    mysqli_stmt_close($stmt_deposit);

    // Insert loan payment record
    $stmt_loan = mysqli_prepare($conn, "INSERT INTO loanpayment (customerid, loanid, paidamt, date) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($stmt_loan, "ssds", $_SESSION['customerid'], $lid, $amt, $dt);
    mysqli_stmt_execute($stmt_loan);
    mysqli_stmt_close($stmt_loan);

    echo "<script language='javascript'> window.location = 'dashboard.php'; </script>";
}

// Handle fixed deposit action securely
if (isset($_POST['fixed'])) {
    $act = $_POST['act'];
    $amount = $_POST['amount'];
    $duration = $_POST['duration'];

    $stmt_fixed_deposit = mysqli_prepare($conn, "INSERT INTO fixed_deposit (customerid, accno, amount, duration, status) VALUES (?, ?, ?, ?, '1')");
    mysqli_stmt_bind_param($stmt_fixed_deposit, "ssss", $_SESSION['customerid'], $act, $amount, $duration);
    mysqli_stmt_execute($stmt_fixed_deposit);
    mysqli_stmt_close($stmt_fixed_deposit);

    echo "<script> swal('Successful!', 'Your Fixed Deposit Account Has Been Created. Your Fixed Deposit Account Number Is " . htmlspecialchars($act) . "', 'success') </script>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .alert-icon { margin-right: 10px; font-size: 25px; }
        .alert-content { display: flex; align-items: top; }
        .alert { padding: 0.75rem 1rem !Important; }
        .icon-circle { display: flex; align-items: center; flex-direction: column; margin: 0 10px; }
        .icon-circle i { border: 2px solid #b6922e; border-radius: 50%; padding: 10px; font-size: 17px; margin-bottom: 7px; color:#b6922e; }
        .icon-circle p { margin: 0; font-size:12.4px; font-weight:600; }
        .icon { width: 60px; height: 60px; line-height: 60px; border-radius: 50%; }
        .icon-text { display: flex; flex-direction: column; align-items: center; text-align: center; margin-top: 10px; }
        @media (max-width: 992px) { .icon-text { margin-top: 0; } }
        .fw-600 { font-weight:600; margin-top:4px; }
        .h34 { height:40px; width:40px; }
        a.ama { color: #495057; }
        a.ama:hover { color: #b6922e; }
        @media (max-width:370px) { .ub { font-size: 11px !important; } }
        @media (max-width:600px) { .bo3 { border-right:none !important; } }
        .bo3 { border-right: 1px #eee solid; }
    </style>
</head>
<body data-sidebar="colored">
    <div id="preloader"> <div id="status"> <div class="spinner-chase"> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> <div class="chase-dot"></div> </div> </div> </div>
    <div id="layout-wrapper">
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row d-none d-md-block">
                        <div class="col-12">
                            <div class="alert border border-primary border-1 alert-dismissible fade show" style="background:#fff; border-left-width: 7px !important; border-radius: 5px; !important;" role="alert">
                                <div class="alert-content">
                                    <i class="bx bx-hash alert-icon text-primary"></i>
                                    <span>
                                        <strong style="display:block;" class="mb-1">Internet Banking Here to help you succeed.</strong>
                                        explore LifeSkills for workplace success and boost your online confidence with Digital Eagles.
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="mb-sm-0 font-size-18" style="text-transform:capitalize;" style="color:#000; font-weight:600;">Welcome <?php echo htmlspecialchars($_SESSION['customername']);?> 👋🏼 </h4>
                                    <small class="mb-sm-0 font-size-12">Last log in, <?php echo htmlspecialchars($_SESSION['lastlogin']); ?></small>
                                </div>
                               <div style="font-weight: 600; color:red;">
    <a href="financial.php" style="color:red; text-decoration:none;">
        <i class="bx bx-rocket" style="color:red;"></i> Get a financial advice.
    </a>
</div>

                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0 me-3">
                                                    <?php if (empty($rowrec1['image'])) { ?>
                                                        <img src="assets/images/users/avatar-1.jpg" alt="" style="object-fit:cover" class="avatar-md rounded-circle img-thumbnail" alt="profile photo">
                                                    <?php } else { ?>
                                                        <img src="assets/images/users/<?php echo htmlspecialchars($rowrec1['image']); ?>" style="object-fit:cover" alt="" class="avatar-md rounded-circle img-thumbnail" alt="profile photo">
                                                    <?php } ?>
                                                </div>
                                                <div class="flex-grow-1 align-self-center">
                                                    <div class="text-muted">
                                                        <h5 class="mb-2" style=" font-family: 'dm sans';"><?php echo htmlspecialchars($_SESSION['customername']); ?>, <?php echo htmlspecialchars($rowrec['accounttype']); ?> <b>A/C</b> <i class="bx bx-chevron-right"></i></h5>
                                                        <h4 class="mb-sm-0 font-size-13" style="color:#000; font-weight:600;">Account No: <?php echo htmlspecialchars($rowrec['accno']); ?>
                                                        <small class="mb-0 font-size-12" style="font-weight:500; text-decoration:underline; color:red;">
    <a href="#trans" style="color:red; text-decoration:underline;">Show recent transactions</a>
</small>

                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-lg-3 col-6 align-self-center">
                                            <div class="text-lg-center mt-4 mt-lg-0">
                                                <div class="row">
                                                    <div class="col-12">
                                                        <div>
                                                            <h4 class="mb-0 rubikfont">
                                                                <?php
$cur = '$';
$balance = $rowrec['accountbalance'];

// Format balance
$formatted = htmlspecialchars($cur) . htmlspecialchars(number_format($balance, 2));

// Add color for positive balance
if ($balance > 0) {
    echo '<span style="color: green;">' . $formatted . '</span>';
} else {
    echo $formatted;
}
?>

                                                            </h4>
                                                            <small class="font-size-12 text-truncate mb-2" style="font-weight:600;">Available Balance</small>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <ul class="metismenu list-unstyled" id="side-menu" 
    style="padding:0; margin:0; list-style:none; font-family:Arial, sans-serif; font-size:14px; background-color:#e0e0e0; border-radius:8px;">

    <li style="margin-bottom:5px;">
        <a href="international.php" class="waves-effect" 
           style="display:flex; align-items:center; padding:10px 15px; color:#111; text-decoration:none; border-radius:6px; background-color:#d6d6d6;">
            <i class='bx bx-credit-card-alt' style="font-size:18px; margin-right:10px;"></i>
            <span>Transfer</span>
        </a>
    </li>

    <li style="margin-bottom:5px;">
        <a href="international.php" class="waves-effect" 
           style="display:flex; align-items:center; padding:10px 15px; color:#111; text-decoration:none; border-radius:6px; background-color:#d6d6d6;">
            <i class='bx bx-euro' style="font-size:18px; margin-right:10px;"></i>
            <span>International Transfer</span>
        </a>
    </li>

    <li style="margin-bottom:5px;">
        <a href="card.php" class="waves-effect" 
           style="display:flex; align-items:center; padding:10px 15px; color:#111; text-decoration:none; border-radius:6px; background-color:#d6d6d6;">
            <i class='bx bx-credit-card' style="font-size:18px; margin-right:10px;"></i>
            <span>Add Card</span>
        </a>
    </li>
    
    <li style="margin-bottom:5px;">
        <a href="register.php" class="waves-effect" 
           style="display:flex; align-items:center; padding:10px 15px; color:#111; text-decoration:none; border-radius:6px; background-color:#d6d6d6;">
            <i class='bx bx-credit-card-alt' style="font-size:18px; margin-right:10px;"></i>
            <span>Add More Accounts</span>
        </a>
    </li>

</ul>

<div class="row" id="trans">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="card-title mb-4">Account Transactions</h4>
                                    
                                    <div style="display:flex; justify-content:flex-end; align-items:center; gap:8px; font-weight:600; font-size:14px;">
    <small class="font-size-14 text-truncate" style="font-weight:600;">Total:</small>
    <h4 class="mb-0 font-size-14" style="margin:0;">
        <?php
        $cur = '$';
        $balance = $rowrec['accountbalance'];

        // Format balance
        $formatted = htmlspecialchars($cur) . htmlspecialchars(number_format($balance, 2));

        // Add color for positive balance
        if ($balance > 0) {
            echo '<span style="color: green;">' . $formatted . '</span>';
        } else {
            echo $formatted;
        }
        ?>
    </h4>
</div>

                                    <div class="table-responsive">
                                        <table class="table align-middle table-nowrap mb-0">
                                            <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">Receiver's Bank</th>
                                                    <th class="align-middle">Amount</th>
                                                    <th class="align-middle">Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                    $query = "SELECT * FROM transfers WHERE sender = ? ORDER BY date DESC";
                                                    $stmt_trans = mysqli_prepare($conn, $query);
                                                    mysqli_stmt_bind_param($stmt_trans, "s", $_SESSION['customerid']);
                                                    mysqli_stmt_execute($stmt_trans);
                                                    $rectrans = mysqli_stmt_get_result($stmt_trans);

                                                    while ($recs = mysqli_fetch_assoc($rectrans)) {
                                                        echo "<tr>";
                                                        echo "<td>TRANS" . htmlspecialchars($recs['id']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($recs['date']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($recs['receiver']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($recs['bank']) . "</td>";
                                                        echo "<td>" . htmlspecialchars($cur) . " " . number_format($recs['amount'], 2) . "</td>";
                                                        echo "<td>";
                                                        if ($recs['status'] == '0') {
                                                            echo "<span class='badge badge-pill badge-soft-danger font-size-11'>Pending</span>";
                                                        } else if ($recs['status'] == '1') {
                                                            echo "<span class='badge badge-pill badge-soft-success font-size-11'>Successful</span>";
                                                        }
                                                        echo "</td>";
                                                        echo "</tr>";
                                                    }
                                                    mysqli_stmt_close($stmt_trans);
                                                ?>
                                            </tbody>
                                        </table>
                                        <div align="left" style="margin-top: 20px;">
                                            <input type="button" class="btn btn-primary" value="Print Transaction Detail" onClick="window.print()">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-lg-7">
                                            <div class="d-flex">
                                                <div class="flex-grow-1 align-self-center bo3">
                                                    <div class="text-muted">
                                                        <h5 class="mb-3 text-primary">Help Bank their future with life insurance</h5>
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="d-flex"><i class="bx bx-check-circle fs-4 me-3"></i><p>It's quick and easy to apply for an Insurance.</p></div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="d-flex"><i class="bx bx-check-circle fs-4 me-3"></i><p>You could get a quote in 2 minutes</p></div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-lg-5 align-self-center">
                                            <div class="text-lg-left mt-4 mt-lg-0">
                                                <div class="row">
                                                    <div class="col-12">
                                                        <div>
                                                            <h5 class="mb-2">T&C's Apply</h5>
                                                            <a href="insurance.php" class="btn btn-primary btn-rounded waves-effect waves-light">Get a quote</a>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    
                  
                  
                  
                    <div class="row">
                        <div class="col-lg-4">
                            <div class="card card-body text-center">
                                <p><img src="ss/1aa.png" class="h34 text-center"></p>
                                <h4 class="card-title">Mortgage Apply Online</h4>
                                <p class="card-text">Whether you're buying a new home, remortgaging, or helping your child onto the property ladder, we have a range of mortgages and tools to help.</p>
                                <a href="mortgage.php" style="font-weight:600;" class="">Explore mortgages <i class="bx bx-chevron-right" style="vertical-align: middle;"></i></a>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="card card-body text-center">
                                <p><img src="ss/2aa.png" class="h34 text-center"></p>
                                <h4 class="card-title">Loans - see personalized rate</h4>
                                <p class="card-text">From home improvements to buying a car or consolidating your debts, there are plenty of reasons you might need a loan.</p>
                                <p class="card-text"><strong>Subject to application, financial circumstances and borrowing history.</strong></p>
                                <a href="#" class="contactLink" style="font-weight:600;">Apply for a loan <i class="bx bx-chevron-right" style="vertical-align: middle;"></i></a>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="card card-body text-center">
                                <p><img src="ss/3aa.png" class="h34 text-center"></p>
                                <h4 class="card-title">Investments</h4>
                                <p class="card-text">Investing could make your money work harder – manage it yourself with Smart Investor or let our experts do it for you with Plan & Invest.</p>
                                <p class="card-text"><strong>The value of investments can fall as well as rise. You may not get back what you invest.</strong></p>
                                <a href="#" class="contactLink" style="font-weight:600;">Start Investment <i class="bx bx-chevron-right" style="vertical-align: middle;"></i></a>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3 justify-content-center">
                        <div class="col-auto">
                            <a href="" id="" class="btn btn-outline-primary waves-effect waves-light contactLink">Explore our products</a>
                        </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/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/libs2/node_modules/datatables.net/js/jquery.dataTables.js"></script>
    <script src="assets/node_modules/libs2/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
    <script src="assets/libs2/custom/data-table.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        // Chart and SweetAlert scripts remain as they were in your original code
        document.addEventListener("DOMContentLoaded", function() {
            const months = [
                'January', 'February', 'March', 'April', 'May', 'June',
                'July', 'August', 'September', 'October', 'November', 'December'
            ];
            const categories = ['Withdrawal', 'Deposit', 'Other Transactions'];
            const seriesData = categories.map(category => ({
                name: category,
                data: Array.from({ length: 12 }, () => 0)
            }));
            var options = {
                chart: {
                    type: 'line',
                    height: 250,
                    width: '100%',
                    toolbar: { show: false }
                },
                series: seriesData,
                xaxis: { categories: months },
                yaxis: { title: { text: 'Amount' } },
                legend: { position: 'top' }
            };
            var chart = new ApexCharts(document.querySelector("#chart"), options);
            chart.render();
        });
        document.querySelectorAll('.contactLink').forEach(function(link) {
            link.addEventListener('click', function(event) {
                event.preventDefault();
                Swal.fire({
                    title: 'To find our products and how to get started, contact our customer care.',
                    icon: 'info',
                    showCancelButton: false,
                    showConfirmButton: true,
                    confirmButtonText: 'OK'
                });
            });
        });
        document.querySelectorAll('.contactLink2').forEach(function(link) {
            link.addEventListener('click', function(event) {
                event.preventDefault();
                Swal.fire({
                    title: 'contact our customer care.',
                    icon: 'info',
                    showCancelButton: false,
                    showConfirmButton: true,
                    confirmButtonText: 'OK'
                });
            });
        });
    </script>
</body>
</html>