<?php
session_start();

if (!isset($_SESSION['chap'])) {
    header("Location: ../index.html#login-area");
    exit();
} else {
    $chap = $_SESSION['chap'];
    include "../connect/db.php";

    $sql = mysqli_query($mysqli, "SELECT * FROM users WHERE email = '$chap'");
    $row = mysqli_fetch_assoc($sql);

    if ($row['status'] == "suspended") {
        header("Location: account.php");
        exit();
    } else if ($row['status'] == "terminated") {
        header("Location: terminate.php");
        exit();
    }

    if ($row['kyc_status'] == "pending" || $row['kyc_status'] == "review") {
        header("Location: kyc.php");
        exit();
    }

    if ($row['code_level'] != "nothing") {
        if ($row['lock_status'] == "active") {
            header("Location: auth.php");
            exit();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en-US" class="js">
<head>
    <?php $pageTitle = $row['firstname'] . ' ' . $row['lastname'] . ' — Dashboard'; ?>
    <?php include 'includes/head.php'; ?>
    <link rel="stylesheet" href="https://www.jqueryscript.net/demo/jQuery-International-Telephone-Input-With-Flags-Dial-Codes/build/css/intlTelInput.css">
</head>
<body class="nk-body npc-crypto bg-white has-sidebar ">
    <div class="nk-app-root">
        <div class="nk-main ">
            <div class="nk-sidebar nk-sidebar-fixed " data-content="sidebarMenu">
                <div class="nk-sidebar-element nk-sidebar-head">
                    <div class="nk-sidebar-brand">
                        <a href="dashboard" class="logo-link nk-sidebar-logo">
                            <img class="logo-light logo-img" src="../logo.png" srcset="../logo.png 2x" alt="logo">
                            <img class="logo-dark logo-img" src="../logo.png" srcset="../logo.png 2x" alt="logo-dark">
                        </a>
                    </div>
                    <div class="nk-menu-trigger mr-n2">
                        <a href="#" class="nk-nav-toggle nk-quick-nav-icon d-xl-none" data-target="sidebarMenu"><em class="icon ni ni-arrow-left"></em></a>
                    </div>
                </div>
              <?php include 'includes/sidebar.php';  ?>

                <div class="nk-content nk-content-fluid">
                    <div class="container-xl wide-lg">
                        <div class="nk-content-body">

                            <!-- Greeting -->
                            <div class="nk-block-head">
                                <div class="nk-block-head-content">
                                    <h4 class="nk-block-title">Welcome, <?=$row['firstname']?></h4>
                                    <p class="nk-block-des">Here's your account at a glance.</p>
                                </div>
                            </div>

                            <!-- Top row: Balance + Checking Account -->
                            <div class="row gy-3 mb-3">
                                <div class="col-lg-6">
                                    <div class="card card-bordered h-100">
                                        <div class="card-inner">
                                            <div class="d-flex align-items-center gap-3 mb-3">
                                                <?php if (!empty($row['img_path'])): ?>
                                                <img src="../<?=$row['img_path']?>" width="52" height="52" class="rounded-circle" alt="">
                                                <?php else: ?>
                                                <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center text-white fw-bold" style="width:52px;height:52px;font-size:1.1rem;">
                                                    <?=strtoupper(substr($row['firstname'],0,1).substr($row['lastname'],0,1))?>
                                                </div>
                                                <?php endif; ?>
                                                <div>
                                                    <div class="fw-bold text-base"><?=$row['firstname']?> <?=$row['lastname']?></div>
                                                    <div class="sub-text">Account: <?=$row['account_num']?></div>
                                                </div>
                                            </div>
                                            <div class="border-top pt-3">
                                                <div class="d-flex justify-content-between align-items-center mb-1">
                                                    <span class="sub-text text-uppercase small">Available Balance</span>
                                                    <a href="#" class="balance-toggle text-muted" title="Hide balance"><em class="icon ni ni-eye"></em></a>
                                                </div>
                                                <div class="d-flex align-items-baseline gap-2">
                                                    <span class="h4 mb-0 fw-bold balance-value"><?=formatCurrency($row['checking_balance'], $row['usercurrency'])?></span>
                                                    <span class="h4 mb-0 fw-bold balance-hidden" style="display:none;">••••••</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="card card-bordered h-100">
                                        <div class="card-inner">
                                            <div class="d-flex justify-content-between align-items-start mb-3">
                                                <div>
                                                    <h6 class="title mb-1">Checking Account</h6>
                                                    <div class="sub-text"><?=maskNumber($row['account_num'], 5)?></div>
                                                </div>
                                                <div class="d-flex gap-2">
                                                    <a href="check-deposit" class="btn btn-sm btn-primary">Deposit</a>
                                                    <a href="transfer" class="btn btn-sm btn-outline-primary">Transfer</a>
                                                </div>
                                            </div>
                                            <div class="border-top pt-3">
                                                <div class="d-flex justify-content-between align-items-center mb-1">
                                                    <span class="sub-text"><?=currencySymbol($row['usercurrency'])?></span>
                                                    <a href="#" class="balance-toggle text-muted" title="Hide balance"><em class="icon ni ni-eye"></em></a>
                                                </div>
                                                <div class="d-flex align-items-baseline gap-2">
                                                    <span class="amount fw-bold fs-5 balance-value"><?=formatCurrency($row['checking_balance'], $row['usercurrency'])?></span>
                                                    <span class="amount fw-bold fs-5 balance-hidden" style="display:none;">••••••</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Second row: Linked Cards + BSL + FICO -->
                            <div class="row gy-3 mb-3">
                                <div class="col-md-4">
                                    <div class="card card-bordered h-100">
                                        <div class="card-inner">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <h6 class="title mb-1">Linked Cards</h6>
                                                    <div class="sub-text">Active debit and virtual cards</div>
                                                </div>
                                                <div class="icon-circle bg-primary-dim text-primary">
                                                    <em class="icon ni ni-cc-alt2-fill"></em>
                                                </div>
                                            </div>
                                            <div class="mt-3">
                                                <span class="h3 fw-bold"><?php $vc = mysqli_query($mysqli, "SELECT COUNT(*) as cnt FROM virtualcard WHERE email = '$chap' AND status IN ('approved','Completed')"); $vcr = mysqli_fetch_assoc($vc); echo ($vcr['cnt'] + intval($row['linked_card'])); ?></span>
                                            </div>
                                            <a href="virtual-card" class="link link-sm mt-2 d-inline-block">View Cards</a>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card card-bordered h-100">
                                        <div class="card-inner">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <h6 class="title mb-1">Credit / Loan</h6>
                                                    <div class="sub-text">Business Support Loan</div>
                                                </div>
                                                <div class="icon-circle bg-warning-dim text-warning">
                                                    <em class="icon ni ni-invest"></em>
                                                </div>
                                            </div>
                                            <div class="mt-3">
                                                <span class="h3 fw-bold"><?=formatCurrency($row['bsl_balance'], $row['usercurrency'])?></span>
                                            </div>
                                            <a href="loan" class="link link-sm mt-2 d-inline-block">View Details</a>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card card-bordered h-100">
                                        <div class="card-inner">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <h6 class="title mb-1">FICO Credit Score</h6>
                                                    <div class="sub-text">Credit health indicator</div>
                                                </div>
                                                <div class="icon-circle bg-success-dim text-success">
                                                    <em class="icon ni ni-check-circle"></em>
                                                </div>
                                            </div>
                                            <div class="mt-3">
                                                <span class="h3 fw-bold"><?=$row['fico_score']?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Bottom row: Transactions + Chart -->
                            <div class="row gy-3">
                                <div class="col-md-6">
                                    <div class="card card-bordered">
                                        <div class="card-head">
                                            <h5 class="title mb-0">Recent Transactions</h5>
                                        </div>
                                        <div class="nk-tb-list">

                                        <?php
                                        $crabs = mysqli_query($mysqli, "SELECT * FROM transactions WHERE user = '$account_num' ORDER BY id DESC LIMIT 10");
                                        $brows = mysqli_num_rows($crabs);

                                        if ($brows == 0):
                                        ?>
                                            <div class="text-center py-5">
                                                <div class="sub-text mb-2">No transactions found.</div>
                                                <p class="text-muted small">Your recent account activity will appear here.</p>
                                            </div>
                                        <?php else:
                                            while ($xrow = mysqli_fetch_assoc($crabs)):
                                                $isDebit = $xrow['type'] == "Debit";
                                                $operator = $isDebit ? "-" : "+";
                                                $color = $isDebit ? 'danger' : 'success';
                                                $txnType = $isDebit ? 'Debited' : 'Credited';
                                                $txnAmount = formatCurrency($xrow['amount'], $row['usercurrency']);
                                        ?>
                                            <div class="nk-tb-item">
                                                <div class="nk-tb-col">
                                                    <span class="tb-sub"><?=$xrow['trans_id']?></span>
                                                </div>
                                                <div class="nk-tb-col">
                                                    <span class="tb-lead"><?=$xrow['description']?></span>
                                                    <span class="tb-date"><?=$xrow['date']?></span>
                                                </div>
                                                <div class="nk-tb-col">
                                                    <span class="tb-amount text-<?=$color?>"><?=$operator?> <?=formatCurrency($xrow['amount'], $row['usercurrency'])?></span>
                                                </div>
                                                <div class="nk-tb-col">
                                                    <span class="badge badge-dim badge-pill badge-outline-primary txn-view-btn" style="cursor:pointer"
                                                          data-ref="<?=$xrow['trans_id']?>"
                                                          data-type="<?=$txnType?>"
                                                          data-amount="<?=$txnAmount?>"
                                                          data-date="<?=$xrow['date']?>"
                                                          data-balance="<?=$row['usercurrency']?> <?=number_format($row['checking_balance'], 2)?>">View</span>
                                                </div>
                                            </div>
                                        <?php endwhile; endif; ?>
                                        </div>
                                        <div class="card-inner border-top text-center">
                                            <a href="summary" class="link link-sm">View All Transactions <em class="icon ni ni-arrow-right"></em></a>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="card card-bordered">
                                        <div class="card-head">
                                            <h5 class="title mb-0">Balance Flow</h5>
                                        </div>
                                        <div class="card-inner text-center">

                                            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
                                            <?php
                                            $count_query = mysqli_query($mysqli, "
                                                SELECT
                                                    SUM(CASE WHEN type = 'Credit' THEN 1 ELSE 0 END) AS credit_count,
                                                    SUM(CASE WHEN type = 'Debit' THEN 1 ELSE 0 END) AS debit_count
                                                FROM transactions
                                                WHERE user = '$account_num'
                                            ");
                                            $result = mysqli_fetch_assoc($count_query);
                                            $credit = $result['credit_count'];
                                            $debit = $result['debit_count'];
                                            ?>
                                            <input type="hidden" id="debit1" value="<?=$debit?>">
                                            <input type="hidden" id="credit1" value="<?=$credit?>">

                                            <canvas class="pie-chart" id="pieChartData" style="max-height:220px;"></canvas>
                                            <script>
                                            var ctx = document.getElementById('pieChartData').getContext('2d');
                                            var pieChart = new Chart(ctx, {
                                                type: 'pie',
                                                data: {
                                                    labels: ['Credit', 'Debit'],
                                                    datasets: [{
                                                        data: [<?=$credit?>, <?=$debit?>],
                                                        backgroundColor: ['#1ee0ac', '#f4aaa4'],
                                                        borderWidth: 1
                                                    }]
                                                },
                                                options: {
                                                    responsive: true,
                                                    plugins: { legend: { position: 'bottom' } }
                                                }
                                            });
                                            </script>
                                        </div>
                                    </div>

                                    <div class="card card-bordered mt-3">
                                        <div class="card-head">
                                            <h5 class="title mb-0">Quick Links</h5>
                                        </div>
                                        <div class="card-inner">
                                            <div class="row g-2">
                                                <div class="col-6"><a href="transfer" class="btn btn-sm btn-outline-primary btn-block">Send Money</a></div>
                                                <div class="col-6"><a href="pay-bills" class="btn btn-sm btn-outline-primary btn-block">Pay Bills</a></div>
                                                <div class="col-6"><a href="virtual-card" class="btn btn-sm btn-outline-primary btn-block">View Cards</a></div>
                                                <div class="col-6"><a href="summary" class="btn btn-sm btn-outline-primary btn-block">Transactions</a></div>
                                                <div class="col-6"><a href="loan" class="btn btn-sm btn-outline-primary btn-block">Apply for Loan</a></div>
                                                <div class="col-6"><a href="contact" class="btn btn-sm btn-outline-primary btn-block">Get Support</a></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

    <!-- Shared Transaction Detail Modal -->
    <div class="modal" tabindex="-1" id="txnModal" role="dialog" aria-modal="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Transaction Details</h5>
                    <a href="#" class="close" data-dismiss="modal" aria-label="Close"><em class="icon ni ni-cross"></em></a>
                </div>
                <div class="modal-body p-4">
                    <ul class="buysell-overview-list">
                        <li class="buysell-overview-item">
                            <span class="pm-currency"><em class="icon ni ni-check-circle-fill"></em> <span id="txnTypeLabel"></span></span>
                            <span class="pm-title" id="txnAmount"></span>
                        </li>
                        <li class="buysell-overview-item">
                            <span class="pm-currency"><em class="icon ni ni-check-circle-fill"></em> <span>Reference:</span></span>
                            <span class="pm-title" id="txnRef"></span>
                        </li>
                        <li class="buysell-overview-item">
                            <span class="pm-currency"><em class="icon ni ni-check-circle-fill"></em> <span>Date:</span></span>
                            <span class="pm-title" id="txnDate"></span>
                        </li>
                        <li class="buysell-overview-item">
                            <span class="pm-currency"><em class="icon ni ni-check-circle-fill"></em> <span>Available Balance:</span></span>
                            <span class="pm-title" id="txnBalance"></span>
                        </li>
                    </ul>
                </div>
                <div class="modal-footer bg-lighter">
                    <span class="sub-text">Processed by <?= htmlspecialchars(getSetting('site_name', 'Deutsche Bank Holdings Delaware')) ?></span>
                </div>
            </div>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.txn-view-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                document.getElementById('txnTypeLabel').textContent = 'Amount ' + this.dataset.type;
                document.getElementById('txnAmount').textContent = this.dataset.amount;
                document.getElementById('txnRef').textContent = this.dataset.ref;
                document.getElementById('txnDate').textContent = this.dataset.date;
                document.getElementById('txnBalance').textContent = this.dataset.balance;
                $('#txnModal').modal('show');
            });
        });
    });
    </script>

    <script>
    // Balance visibility toggle
    document.addEventListener('DOMContentLoaded', function () {
        var hidden = localStorage.getItem('balanceHidden') === 'true';
        function applyState() {
            document.querySelectorAll('.balance-toggle').forEach(function (btn) {
                var icon = btn.querySelector('.icon');
                if (hidden) {
                    icon.classList.remove('ni-eye');
                    icon.classList.add('ni-eye-off');
                    btn.setAttribute('title', 'Show balance');
                } else {
                    icon.classList.remove('ni-eye-off');
                    icon.classList.add('ni-eye');
                    btn.setAttribute('title', 'Hide balance');
                }
            });
            document.querySelectorAll('.balance-value').forEach(function (el) {
                el.style.display = hidden ? 'none' : '';
            });
            document.querySelectorAll('.balance-hidden').forEach(function (el) {
                el.style.display = hidden ? '' : 'none';
            });
        }
        applyState();
        document.querySelectorAll('.balance-toggle').forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                hidden = !hidden;
                localStorage.setItem('balanceHidden', hidden);
                applyState();
            });
        });
    });
    </script>

    <?php include 'includes/footer.php'; ?>
