<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
include('includes/session.inc');
$Title = _('Customer Receipt') . '/' . _('Credit Note Allocations');
$ViewTopic= 'ARTransactions';
$BookMark = 'CustomerAllocations';
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');
$userid = $_SESSION['UserID'];

/* ── Direct mysqli for dashboard KPIs ── */
$db_host = 'localhost';
$db_user = 'sooggoo';
$db_pass = '4Compassion*';
$db_name = isset($_SESSION['DatabaseName']) ? $_SESSION['DatabaseName'] : 'evergreenint';
$dbc = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($dbc->connect_error) { $dbc = null; }

/* ── KPI Queries ── */
$kpi_total = 0; $kpi_today = 0; $kpi_today_amt = 0; $kpi_month_amt = 0;
$kpi_pending_bank = 0; $kpi_cancelled = 0; $kpi_cash = 0; $kpi_cheque = 0;
$kpi_eftpos = 0; $kpi_dd = 0;

if ($dbc) {
    // Total receipts
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM debtortrans WHERE type=12");
    if ($r && $row = $r->fetch_assoc()) { $kpi_total = (int)$row['cnt']; }

    // Today's receipts & amount
    $r = $dbc->query("SELECT COUNT(*) AS cnt, COALESCE(SUM(ABS(ovamount)),0) AS amt FROM debtortrans WHERE type=12 AND DATE(trandate) = CURDATE()");
    if ($r && $row = $r->fetch_assoc()) { $kpi_today = (int)$row['cnt']; $kpi_today_amt = (float)$row['amt']; }

    // This month amount
    $r = $dbc->query("SELECT COALESCE(SUM(ABS(ovamount)),0) AS amt FROM debtortrans WHERE type=12 AND YEAR(trandate)=YEAR(CURDATE()) AND MONTH(trandate)=MONTH(CURDATE())");
    if ($r && $row = $r->fetch_assoc()) { $kpi_month_amt = (float)$row['amt']; }

    // Pending banking
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM debtortrans WHERE type=12 AND (receipt_banked=0 OR receipt_banked IS NULL) AND (cancelled=0 OR cancelled IS NULL)");
    if ($r && $row = $r->fetch_assoc()) { $kpi_pending_bank = (int)$row['cnt']; }

    // Cancelled
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM debtortrans WHERE type=12 AND cancelled=1");
    if ($r && $row = $r->fetch_assoc()) { $kpi_cancelled = (int)$row['cnt']; }

    // Payment method breakdown (this month)
    $r = $dbc->query("SELECT payment_method, COUNT(*) AS cnt FROM debtortrans WHERE type=12 AND YEAR(trandate)=YEAR(CURDATE()) AND MONTH(trandate)=MONTH(CURDATE()) GROUP BY payment_method");
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            $pm = strtolower(trim($row['payment_method']));
            if ($pm == 'cash') $kpi_cash = (int)$row['cnt'];
            elseif ($pm == 'cheque') $kpi_cheque = (int)$row['cnt'];
            elseif ($pm == 'efpos' || $pm == 'eftpos') $kpi_eftpos = (int)$row['cnt'];
            elseif ($pm == 'direct deposit') $kpi_dd = (int)$row['cnt'];
        }
    }

    // Recent 5 receipts for panel
    $recent_receipts = array();
    $r = $dbc->query("SELECT dt.transno, dt.trandate, dt.ovamount, dt.payment_method, dt.entered_by, dm.name AS customer_name
                       FROM debtortrans dt
                       LEFT JOIN debtorsmaster dm ON dt.debtorno = dm.debtorno
                       WHERE dt.type=12
                       ORDER BY dt.id DESC LIMIT 5");
    if ($r) {
        while ($row = $r->fetch_assoc()) { $recent_receipts[] = $row; }
    }
}
?>

<!-- ============================================================
     ENHANCED UI: Ant Design Style + Teal Branding
     ============================================================ -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>

<style>
/* ── Base ── */
.rcpt-wrap * { box-sizing: border-box; }
.rcpt-wrap {
    font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
    color: #1F2937;
    max-width: 1440px;
    margin: 0 auto;
    padding: 0 20px 40px;
}

/* ── Gradient Banner ── */
.rcpt-banner {
    background: linear-gradient(135deg, #1E8F96 0%, #2AABB3 50%, #35C4CD 100%);
    border-radius: 16px;
    padding: 32px 36px;
    margin: 20px 0 24px;
    color: #fff;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(42,171,179,0.3);
}
.rcpt-banner::before {
    content: '';
    position: absolute;
    top: -40px; right: -40px;
    width: 200px; height: 200px;
    background: rgba(255,255,255,0.06);
    border-radius: 50%;
}
.rcpt-banner::after {
    content: '';
    position: absolute;
    bottom: -60px; right: 80px;
    width: 160px; height: 160px;
    background: rgba(255,255,255,0.04);
    border-radius: 50%;
}
.rcpt-banner h1 {
    font-size: 26px; font-weight: 700;
    margin: 0 0 6px; letter-spacing: -0.3px;
}
.rcpt-banner p {
    font-size: 14px; opacity: 0.9; margin: 0; font-weight: 300;
}
.rcpt-breadcrumb {
    display: flex; align-items: center; gap: 8px;
    font-size: 13px; color: rgba(255,255,255,0.8); margin-bottom: 12px;
}
.rcpt-breadcrumb a { color: rgba(255,255,255,0.8); text-decoration: none; }
.rcpt-breadcrumb a:hover { color: #fff; }
.rcpt-breadcrumb .sep { opacity: 0.5; }
.rcpt-banner-stats {
    display: flex; gap: 32px; margin-top: 18px;
    padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.15);
}
.rcpt-banner-stat .stat-val {
    font-size: 22px; font-weight: 700;
}
.rcpt-banner-stat .stat-lbl {
    font-size: 11px; opacity: 0.8; text-transform: uppercase; letter-spacing: 0.5px;
}

/* ── Dashboard Toggle ── */
.rcpt-dash-toggle {
    display: flex; align-items: center; gap: 8px;
    cursor: pointer; font-size: 13px; color: #6B7280; font-weight: 500;
    margin-bottom: 16px; user-select: none;
    padding: 8px 14px; background: #F9FAFB; border-radius: 8px;
    width: fit-content; transition: color 0.2s;
}
.rcpt-dash-toggle:hover { color: #2AABB3; }
.rcpt-dash-toggle i { transition: transform 0.3s; font-size: 11px; }
.rcpt-dash-toggle.collapsed i { transform: rotate(-90deg); }
.rcpt-dash-wrap {
    overflow: hidden; transition: max-height 0.4s ease, opacity 0.3s;
    max-height: 800px; opacity: 1;
}
.rcpt-dash-wrap.collapsed { max-height: 0; opacity: 0; }

/* ── KPI Grid ── */
.rcpt-kpi-grid {
    display: grid; grid-template-columns: repeat(4, 1fr);
    gap: 16px; margin-bottom: 20px;
}
.rcpt-kpi {
    background: #fff; border-radius: 12px;
    padding: 20px 22px; border-left: 4px solid #2AABB3;
    box-shadow: 0 1px 8px rgba(0,0,0,0.06);
    transition: transform 0.2s, box-shadow 0.2s;
}
.rcpt-kpi:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}
.rcpt-kpi-icon {
    width: 42px; height: 42px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px; margin-bottom: 12px;
}
.rcpt-kpi-icon.teal   { background: #E6F7F8; color: #2AABB3; }
.rcpt-kpi-icon.green  { background: #E8F8E8; color: #52C41A; }
.rcpt-kpi-icon.orange { background: #FFF4E6; color: #FAAD14; }
.rcpt-kpi-icon.blue   { background: #E8F4FD; color: #1890FF; }
.rcpt-kpi-icon.red    { background: #FFF1F0; color: #FF4D4F; }
.rcpt-kpi-icon.purple { background: #F3E8FF; color: #722ED1; }
.rcpt-kpi .kpi-value {
    font-size: 26px; font-weight: 700; color: #1F2937; line-height: 1.1;
}
.rcpt-kpi .kpi-label {
    font-size: 12px; color: #6B7280; font-weight: 500;
    text-transform: uppercase; letter-spacing: 0.5px; margin-top: 4px;
}

/* ── Dashboard Panels Row ── */
.rcpt-panels {
    display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 20px;
}
.rcpt-panel {
    background: #fff; border-radius: 12px;
    box-shadow: 0 1px 8px rgba(0,0,0,0.06);
    border: 1px solid #E5E7EB; overflow: hidden;
}
.rcpt-panel-head {
    padding: 14px 20px; border-bottom: 1px solid #F0F0F0;
    display: flex; align-items: center; gap: 10px;
    font-weight: 600; font-size: 14px; color: #1F2937;
    background: #FAFBFC;
}
.rcpt-panel-head i {
    color: #2AABB3; font-size: 15px;
}
.rcpt-panel-body { padding: 16px 20px; }

/* Recent receipt rows */
.rcpt-recent-row {
    display: flex; justify-content: space-between; align-items: center;
    padding: 10px 0; border-bottom: 1px solid #F5F5F5;
}
.rcpt-recent-row:last-child { border-bottom: none; }
.rcpt-recent-left { display: flex; align-items: center; gap: 12px; }
.rcpt-recent-avatar {
    width: 36px; height: 36px; border-radius: 8px;
    background: #E6F7F8; color: #2AABB3;
    display: flex; align-items: center; justify-content: center;
    font-weight: 700; font-size: 13px;
}
.rcpt-recent-info .rcpt-name { font-size: 13px; font-weight: 600; color: #1F2937; }
.rcpt-recent-info .rcpt-meta { font-size: 11px; color: #9CA3AF; }
.rcpt-recent-amt {
    font-size: 14px; font-weight: 700; color: #1E8F96; text-align: right;
}
.rcpt-recent-amt .method-badge {
    display: inline-block; font-size: 10px; font-weight: 600;
    padding: 2px 8px; border-radius: 10px; margin-top: 2px;
}
.method-cash { background: #E8F8E8; color: #389E0D; }
.method-cheque { background: #FFF4E6; color: #AD6800; }
.method-eftpos { background: #E8F4FD; color: #096DD9; }
.method-dd { background: #F3E8FF; color: #531DAB; }
.method-cc { background: #FFF1F0; color: #CF1322; }

/* Chart canvas */
.rcpt-chart-wrap { position: relative; height: 200px; }




/* ── Responsive ── */
@media (max-width: 1024px) {
    .rcpt-kpi-grid { grid-template-columns: repeat(2, 1fr); }
    .rcpt-panels { grid-template-columns: 1fr; }
}
@media (max-width: 640px) {
    .rcpt-kpi-grid { grid-template-columns: 1fr; }
    .rcpt-banner { padding: 24px 20px; }
    .rcpt-banner h1 { font-size: 20px; }
    .rcpt-banner-stats { flex-wrap: wrap; gap: 16px; }
}
</style>

<div class="rcpt-wrap">

<!-- ── Banner ── -->
<div class="rcpt-banner">
    <div class="rcpt-breadcrumb">
        <a href="index.php"><i class="fas fa-home"></i></a>
        <span class="sep">/</span>
        <a href="index.php">Accounts Receivable</a>
        <span class="sep">/</span>
        <span>Customer Receipts</span>
    </div>
    <h1><i class="fas fa-receipt" style="margin-right:10px;opacity:0.9;"></i>Customer Receipts</h1>
    <p>Manage customer payments, allocations, and receipt processing</p>
    <div class="rcpt-banner-stats">
        <div class="rcpt-banner-stat">
            <div class="stat-val"><?php echo number_format($kpi_today); ?></div>
            <div class="stat-lbl">Receipts Today</div>
        </div>
        <div class="rcpt-banner-stat">
            <div class="stat-val">$<?php echo number_format($kpi_today_amt, 2); ?></div>
            <div class="stat-lbl">Collected Today</div>
        </div>
        <div class="rcpt-banner-stat">
            <div class="stat-val">$<?php echo number_format($kpi_month_amt, 2); ?></div>
            <div class="stat-lbl">This Month</div>
        </div>
        <div class="rcpt-banner-stat">
            <div class="stat-val"><?php echo number_format($kpi_pending_bank); ?></div>
            <div class="stat-lbl">Pending Banking</div>
        </div>
    </div>
</div>

<!-- ── Dashboard Toggle ── -->
<div class="rcpt-dash-toggle" id="rcptDashToggle" onclick="toggleRcptDash()">
    <i class="fas fa-chevron-down"></i>
    <span>Dashboard Overview</span>
</div>

<div class="rcpt-dash-wrap" id="rcptDashWrap">
    <!-- KPI Cards -->
    <div class="rcpt-kpi-grid">
        <div class="rcpt-kpi">
            <div class="rcpt-kpi-icon teal"><i class="fas fa-file-invoice-dollar"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_total); ?></div>
            <div class="kpi-label">Total Receipts</div>
        </div>
        <div class="rcpt-kpi" style="border-left-color:#52C41A;">
            <div class="rcpt-kpi-icon green"><i class="fas fa-money-bill-wave"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_cash); ?></div>
            <div class="kpi-label">Cash (This Month)</div>
        </div>
        <div class="rcpt-kpi" style="border-left-color:#FAAD14;">
            <div class="rcpt-kpi-icon orange"><i class="fas fa-money-check"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_cheque); ?></div>
            <div class="kpi-label">Cheque (This Month)</div>
        </div>
        <div class="rcpt-kpi" style="border-left-color:#1890FF;">
            <div class="rcpt-kpi-icon blue"><i class="fas fa-credit-card"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_eftpos + $kpi_dd); ?></div>
            <div class="kpi-label">Electronic (This Month)</div>
        </div>
    </div>

    <!-- Panels Row -->
    <div class="rcpt-panels">
        <!-- Recent Receipts -->
        <div class="rcpt-panel">
            <div class="rcpt-panel-head">
                <i class="fas fa-clock-rotate-left"></i> Recent Receipts
            </div>
            <div class="rcpt-panel-body">
                <?php if (count($recent_receipts) > 0): ?>
                    <?php foreach ($recent_receipts as $rr):
                        $cname = isset($rr['customer_name']) ? $rr['customer_name'] : 'Unknown';
                        $initials = '';
                        $parts = explode(' ', $cname);
                        foreach ($parts as $p) { if ($p) $initials .= strtoupper($p[0]); if (strlen($initials) >= 2) break; }
                        if (!$initials) $initials = '??';
                        $pm = strtolower(trim(isset($rr['payment_method']) ? $rr['payment_method'] : ''));
                        $pmClass = 'method-cash';
                        $pmLabel = ucfirst($pm);
                        if ($pm == 'cheque') $pmClass = 'method-cheque';
                        elseif ($pm == 'efpos' || $pm == 'eftpos') { $pmClass = 'method-eftpos'; $pmLabel = 'EFTPOS'; }
                        elseif ($pm == 'direct deposit') { $pmClass = 'method-dd'; $pmLabel = 'Direct Deposit'; }
                        elseif ($pm == 'credit card') { $pmClass = 'method-cc'; $pmLabel = 'Credit Card'; }
                    ?>
                    <div class="rcpt-recent-row">
                        <div class="rcpt-recent-left">
                            <div class="rcpt-recent-avatar"><?php echo $initials; ?></div>
                            <div class="rcpt-recent-info">
                                <div class="rcpt-name"><?php echo htmlspecialchars(substr($cname, 0, 30)); ?></div>
                                <div class="rcpt-meta">#<?php echo $rr['transno']; ?> &middot; <?php echo $rr['trandate']; ?></div>
                            </div>
                        </div>
                        <div class="rcpt-recent-amt">
                            $<?php echo number_format(abs((float)$rr['ovamount']), 2); ?>
                            <br><span class="method-badge <?php echo $pmClass; ?>"><?php echo $pmLabel; ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div style="text-align:center;padding:20px;color:#9CA3AF;">
                        <i class="fas fa-inbox" style="font-size:32px;margin-bottom:8px;color:#D1D5DB;"></i>
                        <p style="margin:0;font-size:13px;">No recent receipts found</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Payment Mix Chart -->
        <div class="rcpt-panel">
            <div class="rcpt-panel-head">
                <i class="fas fa-chart-pie"></i> Payment Methods (This Month)
            </div>
            <div class="rcpt-panel-body">
                <div class="rcpt-chart-wrap">
                    <canvas id="rcptPayChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ── XCRUD Table (untouched) ── -->
        <?php
        echo '<div class="col-sm-12">';

        include('xcrud/xcrud.php');
        $ebusiness = Xcrud::get_instance();
        $ebusiness->table('debtortrans');
        $ebusiness->table_name('Receipts Listings');
        $ebusiness->where('type','12');
        $ebusiness->relation('department','department','departmentid','departmentname');
        $ebusiness->relation('bank','bankaccounts','accountcode',array('bankaccountnumber','bankaccountname'));
        $ebusiness->relation('debtorno','debtorsmaster','debtorno',array('name','debtorno'));
        $ebusiness->relation('electronic_bank_details','bankaccounts','oldglcode',array('bank_name','bankaccountnumber','oldglcode'));
        $ebusiness->relation('account_number','debtoraccount','account_number',array('account_number','billing_name'),'','','','','','debtorno','debtorno');
        $ebusiness->order_by('id','desc');
        $ebusiness->button('CancelReceipt.php?id={id}&transno={transno}', 'Cancel this Receipt','glyphicon glyphicon-retweet','approve');
        $ebusiness->button('PDFReceipt.php?id={id}&transno={transno}', 'Print Receipt','glyphicon glyphicon-download-alt','westpac');
        $ebusiness->button('CustomerAllocations.php?account={account_number}&debtorno={debtorno}&transno={transno}', 'Allocations','glyphicon glyphicon-list-alt','westpac');

        $ebusiness->column_name('transno','Receipt Number');
        $ebusiness->column_name('debtorno','customer:');
        $ebusiness->label('debtorno','customer:');
        $ebusiness->column_name('inputdate','Date:');
        $ebusiness->column_name('ovamount','Amount Paid:');
        $ebusiness->label('transno','Receipt No:');
        $ebusiness->label('manual_inv_number','Manual Receipt No:');
        $ebusiness->label('ovamount','Amount Paid:');
        $ebusiness->sum('ovamount');
        $ebusiness->columns('id,transno,type,department,trandate,manual_inv_number,debtorno,account_number,ovamount,payment_method,electronic_bank_details,electronic_bank_date,reference,entered_by,entered_date,receipt_banked,drawer_bank,drawer_accountnumber,drawer_chqnumber,cancelled,cancelled_by,cancel_reason,settled');
        $ebusiness->fields('id,transno,type,department,trandate,manual_inv_number,debtorno,account_number,ovamount,payment_method,electronic_bank_details,electronic_bank_date,receipt_banked,reference,drawer_bank,drawer_accountnumber,drawer_chqnumber,entered_by,entered_date,cancelled,cancelled_by,cancel_reason,settled');
        $ebusiness->disabled('type,cancelled,cancelled_by,cancel_reason,receipt_banked');
        $ebusiness->set_attr('trandate',array('required'=>'required'));
        $ebusiness->set_attr('debtorno',array('required'=>'required'));
        $ebusiness->set_attr('account_number',array('required'=>'required'));
        $ebusiness->change_type('payment_method','select','Cash','Cash,Cheque,EFPOS,Credit Card,Direct Deposit');
        $ebusiness->set_attr('payment_method',array('id'=>'payment_method'));
        $ebusiness->set_attr('electronic_bank_details',array('id'=>'electronic_bank_details'));
        $ebusiness->set_attr('electronic_bank_date',array('id'=>'electronic_bank_date'));
        $ebusiness->set_attr('receipt_banked',array('id'=>'banked'));
        $ebusiness->set_attr('payment_method',array('required'=>'required'));
        $ebusiness->set_attr('drawer_bank',array('id'=>'drawer_bank'));
        $ebusiness->set_attr('drawer_accountnumber',array('id'=>'drawer_accountnumber'));
        $ebusiness->set_attr('drawer_chqnumber',array('id'=>'drawer_chqnumber'));
        $ebusiness->set_attr('ovamount',array('id'=>'ovamount','required'=>'required'));
        $ebusiness->unset_remove();
        $ebusiness->unset_view();
        $userfullname = $_SESSION['UsersRealName'];
        $ebusiness->pass_var('settled','0');
        $ebusiness->pass_var('entered_by',$userfullname);
        $ebusiness->pass_var('type','12');

        if ($userid == 'roneelp' || $userid=='saula' || $userid=='ronil' || $userid=='vineshkumar'){
            $ebusiness->pass_default('department','14');
            $ebusiness->pass_var('department','14');
        }
        if ($userid == 'rowen' || $userid=='rramlu'){
            $ebusiness->pass_default('department','31');
            $ebusiness->pass_var('department','31');
        }
        $ebusiness->before_insert('addreceipt','functionreceipt.php');
        $ebusiness->before_update('updatereceipt','functionreceipt.php');

        echo $ebusiness->render();
        echo '</div>';
        ?>

</div><!-- end rcpt-wrap -->

<!-- ── JavaScript ── -->
<script>
// Dashboard toggle with localStorage
function toggleRcptDash() {
    var wrap = document.getElementById('rcptDashWrap');
    var toggle = document.getElementById('rcptDashToggle');
    if (wrap.classList.contains('collapsed')) {
        wrap.classList.remove('collapsed');
        toggle.classList.remove('collapsed');
        localStorage.setItem('rcptDashCollapsed', 'false');
    } else {
        wrap.classList.add('collapsed');
        toggle.classList.add('collapsed');
        localStorage.setItem('rcptDashCollapsed', 'true');
    }
}
(function(){
    if (localStorage.getItem('rcptDashCollapsed') === 'true') {
        document.getElementById('rcptDashWrap').classList.add('collapsed');
        document.getElementById('rcptDashToggle').classList.add('collapsed');
    }
})();

// Payment Methods Doughnut Chart
document.addEventListener('DOMContentLoaded', function(){
    var ctx = document.getElementById('rcptPayChart');
    if (ctx) {
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['Cash', 'Cheque', 'EFTPOS', 'Direct Deposit'],
                datasets: [{
                    data: [<?php echo $kpi_cash; ?>, <?php echo $kpi_cheque; ?>, <?php echo $kpi_eftpos; ?>, <?php echo $kpi_dd; ?>],
                    backgroundColor: ['#52C41A', '#FAAD14', '#1890FF', '#722ED1'],
                    borderWidth: 0,
                    hoverOffset: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '65%',
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            font: { family: 'Poppins', size: 12, weight: '500' },
                            color: '#4B5563',
                            padding: 14,
                            usePointStyle: true,
                            pointStyleWidth: 10
                        }
                    }
                }
            }
        });
    }
});
</script>

<!-- ── Existing XCRUD JS Logic (Payment method toggles, ovamount negation) ── -->
<script type="text/javascript">
jQuery(document).ready(function($){

    // Auto-negate ovamount (receipts stored as negative)
    $(".xcrud").on("blur","#ovamount",function(){
        var ovamount = $("#ovamount").val();
        if (ovamount > 0) {
            $("#ovamount").val('-' + ovamount);
        }
    });

    // Payment method conditional fields
    $(".xcrud").on("change","#payment_method",function(){
        var payment_method = $("#payment_method").val();
        var v = parseInt(1);
        var z = parseInt(0);

        if (payment_method == "EFPOS" || payment_method == "Credit Card" || payment_method == "Direct Deposit") {
            $("#banked").val(v);
            $("#electronic_bank_date").show();
            $("#electronic_bank_details").show();
            $("#electronic_bank_date").prop('required',true);
            $("#electronic_bank_details").prop('required',true);
            $("#drawer_bank").hide();
            $("#drawer_accountnumber").hide();
            $("#drawer_chqnumber").hide();

            var methodName = payment_method;
            if (payment_method == "EFPOS") methodName = "EFTPOS";

            // Styled alert replacement
            var $alert = $('<div style="position:fixed;top:20px;right:20px;z-index:99999;background:linear-gradient(135deg,#2AABB3,#1E8F96);color:#fff;padding:16px 24px;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,0.2);font-family:Poppins,sans-serif;font-size:13px;font-weight:500;max-width:400px;animation:slideIn 0.3s ease;"><i class="fas fa-info-circle" style="margin-right:8px;"></i>Since you selected <b>' + methodName + '</b>, please fill in the electronic bank details and date fields.</div>');
            $('body').append($alert);
            setTimeout(function(){ $alert.fadeOut(400, function(){ $(this).remove(); }); }, 4000);

        } else {
            $("#banked").val(z);
            $("#electronic_bank_date").prop('required',false);
            $("#electronic_bank_details").prop('required',false);
            $("#electronic_bank_date").hide();
            $("#electronic_bank_details").hide();
            $("#drawer_bank").show();
            $("#drawer_accountnumber").show();
            $("#drawer_chqnumber").show();
        }
    });
});

jQuery(document).on("ready xcrudafterrequest",function(){
});
</script>

<style>
@keyframes slideIn {
    from { transform: translateX(100px); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}
</style>

<?php
// ── Footer / Menu Logic (preserved) ──
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
    echo '<table class="table_index">
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p></td></tr>
        </table>';
    include('includes/footer.inc');
    exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
    echo '<table class="table_index">
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p></td></tr>
        </table>';
    include('includes/footer.inc');
    exit;
}

if (isset($_GET['Application'])){
    $_SESSION['Module'] = $_GET['Application'];
}

function GetRptLinks($GroupID) {
    global $db, $RootPath, $ReportList;
    require_once('reportwriter/languages/en_US/reports.php');
    require_once('reportwriter/admin/defaults.php');
    $GroupID=$ReportList[$GroupID];
    $Title= array(_('Custom Reports'), _('Standard Reports and Forms'));
    $sql= "SELECT id, reporttype, defaultreport, groupname, reportname FROM reports ORDER BY groupname, reportname";
    $Result=DB_query($sql,'','',false,true);
    $ReportList = '';
    while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;
    $RptLinks = '';
    for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers"><b>' .  $Title[$Def] . '</b></li>';
        $NoEntries = true;
        if ($ReportList) {
            foreach ($ReportList as $Report) {
                if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p></li>';
                    $NoEntries = false;
                }
            }
            $NoForms = true;
            foreach ($ReportList as $Report) {
                $Group=explode(':',$Report['groupname']);
                if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>' . $FormGroups[$Report['groupname']] . '</a></li>';
                    $NoForms = false;
                    $NoEntries = false;
                }
            }
        }
        if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
    }
    return $RptLinks;
}

if ($dbc) { $dbc->close(); }
?>
