<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
ob_start();
include('includes/session.inc');
$Title=_('PAYE Report');
include('includes/newheader.php');

include('includes/SQL_CommonFunctions.inc');
include('includes/GetPaymentMethods.php');
include('includes/GetPrice.inc');

/* ─── Loading Modal (render first, then flush) ─── */
?>
<div id="paye-loading-modal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.95);z-index:99999;display:flex;align-items:center;justify-content:center;flex-direction:column;">
    <div style="text-align:center;">
        <div style="width:48px;height:48px;border:4px solid #E6F7F8;border-top:4px solid #2AABB3;border-radius:50%;animation:paye-spin 0.8s linear infinite;margin:0 auto 16px;"></div>
        <p style="font-family:'Poppins',sans-serif;color:#1F2937;font-size:15px;margin:0;">Loading PAYE Tax Dashboard...</p>
        <p id="paye-load-timer" style="font-family:'Poppins',sans-serif;color:#9CA3AF;font-size:12px;margin:6px 0 0;"></p>
    </div>
</div>
<style>@keyframes paye-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>
<script>
var _payeStart=Date.now();
var _payeTimer=setInterval(function(){
    var s=((Date.now()-_payeStart)/1000).toFixed(1);
    var el=document.getElementById('paye-load-timer');
    if(el) el.textContent=s+'s';
},100);
</script>
<?php
if(ob_get_level()) { ob_flush(); }
flush();

/* ─── Dashboard Data (direct mysqli) ─── */
$dbc = new mysqli('localhost', 'sooggoo', '4Compassion*', 'evergreenint');
if($dbc->connect_error) { $dbc = null; }

$currentYear = date('Y');
$lastYear = $currentYear - 1;

// Initialize dashboard data
$dash = array(
    'cy_paye' => 0, 'cy_gross' => 0, 'cy_srt' => 0, 'cy_ecal' => 0, 'cy_employees' => 0,
    'ly_paye' => 0, 'ly_gross' => 0, 'ly_srt' => 0, 'ly_ecal' => 0, 'ly_employees' => 0,
    'monthly_cy' => array(), 'monthly_ly' => array(),
    'top_paye' => array(), 'dept_breakdown' => array()
);

if($dbc) {
    // Current year totals
    $sql = "SELECT 
                COUNT(DISTINCT pd.employeeid) as emp_count,
                COALESCE(SUM(pd.income_tax_to_withhold),0) as total_paye,
                COALESCE(SUM(pd.totalgross_amount),0) as total_gross,
                COALESCE(SUM(pd.srt_tax_to_withhold),0) as total_srt,
                COALESCE(SUM(pd.ecal_tax_to_withhold),0) as total_ecal
            FROM payrun_details pd
            INNER JOIN calendar_management cm ON pd.id = cm.id
            WHERE YEAR(cm.end_date) = $currentYear";
    $r = $dbc->query($sql);
    if($r && $row = $r->fetch_assoc()) {
        $dash['cy_paye'] = round($row['total_paye'], 2);
        $dash['cy_gross'] = round($row['total_gross'], 2);
        $dash['cy_srt'] = round($row['total_srt'], 2);
        $dash['cy_ecal'] = round($row['total_ecal'], 2);
        $dash['cy_employees'] = intval($row['emp_count']);
    }

    // Last year totals
    $sql = "SELECT 
                COUNT(DISTINCT pd.employeeid) as emp_count,
                COALESCE(SUM(pd.income_tax_to_withhold),0) as total_paye,
                COALESCE(SUM(pd.totalgross_amount),0) as total_gross,
                COALESCE(SUM(pd.srt_tax_to_withhold),0) as total_srt,
                COALESCE(SUM(pd.ecal_tax_to_withhold),0) as total_ecal
            FROM payrun_details pd
            INNER JOIN calendar_management cm ON pd.id = cm.id
            WHERE YEAR(cm.end_date) = $lastYear";
    $r = $dbc->query($sql);
    if($r && $row = $r->fetch_assoc()) {
        $dash['ly_paye'] = round($row['total_paye'], 2);
        $dash['ly_gross'] = round($row['total_gross'], 2);
        $dash['ly_srt'] = round($row['total_srt'], 2);
        $dash['ly_ecal'] = round($row['total_ecal'], 2);
        $dash['ly_employees'] = intval($row['emp_count']);
    }

    // Monthly breakdown - current year
    $sql = "SELECT 
                MONTH(cm.end_date) as mth,
                COALESCE(SUM(pd.income_tax_to_withhold),0) as paye,
                COALESCE(SUM(pd.totalgross_amount),0) as gross,
                COALESCE(SUM(pd.srt_tax_to_withhold),0) as srt,
                COALESCE(SUM(pd.ecal_tax_to_withhold),0) as ecal
            FROM payrun_details pd
            INNER JOIN calendar_management cm ON pd.id = cm.id
            WHERE YEAR(cm.end_date) = $currentYear
            GROUP BY MONTH(cm.end_date)
            ORDER BY mth";
    $r = $dbc->query($sql);
    if($r) { while($row = $r->fetch_assoc()) { $dash['monthly_cy'][] = $row; } }

    // Monthly breakdown - last year
    $sql = "SELECT 
                MONTH(cm.end_date) as mth,
                COALESCE(SUM(pd.income_tax_to_withhold),0) as paye,
                COALESCE(SUM(pd.totalgross_amount),0) as gross,
                COALESCE(SUM(pd.srt_tax_to_withhold),0) as srt,
                COALESCE(SUM(pd.ecal_tax_to_withhold),0) as ecal
            FROM payrun_details pd
            INNER JOIN calendar_management cm ON pd.id = cm.id
            WHERE YEAR(cm.end_date) = $lastYear
            GROUP BY MONTH(cm.end_date)
            ORDER BY mth";
    $r = $dbc->query($sql);
    if($r) { while($row = $r->fetch_assoc()) { $dash['monthly_ly'][] = $row; } }

    // Top 10 PAYE contributors this year
    $sql = "SELECT 
                pd.employeeid,
                CONCAT(em.first_name, ' ', em.last_name) as full_name,
                COALESCE(dept.departmentname, 'Unassigned') as departmentname,
                COALESCE(SUM(pd.income_tax_to_withhold),0) as total_paye,
                COALESCE(SUM(pd.totalgross_amount),0) as total_gross
            FROM payrun_details pd
            INNER JOIN calendar_management cm ON pd.id = cm.id
            INNER JOIN employeemaster em ON pd.employeeid = em.employeeid
            LEFT JOIN department dept ON em.department = dept.departmentid
            WHERE YEAR(cm.end_date) = $currentYear
            GROUP BY pd.employeeid
            ORDER BY total_paye DESC
            LIMIT 10";
    $r = $dbc->query($sql);
    if($r) { while($row = $r->fetch_assoc()) { $dash['top_paye'][] = $row; } }

    // Department breakdown this year
    $sql = "SELECT 
                COALESCE(dept.departmentname, 'Unassigned') as dept,
                COUNT(DISTINCT pd.employeeid) as emp_count,
                COALESCE(SUM(pd.income_tax_to_withhold),0) as total_paye,
                COALESCE(SUM(pd.totalgross_amount),0) as total_gross
            FROM payrun_details pd
            INNER JOIN calendar_management cm ON pd.id = cm.id
            INNER JOIN employeemaster em ON pd.employeeid = em.employeeid
            LEFT JOIN department dept ON em.department = dept.departmentid
            WHERE YEAR(cm.end_date) = $currentYear
            GROUP BY dept.departmentname
            ORDER BY total_paye DESC";
    $r = $dbc->query($sql);
    if($r) { while($row = $r->fetch_assoc()) { $dash['dept_breakdown'][] = $row; } }

    $dbc->close();
}

// Calculate YoY changes
$paye_change = ($dash['ly_paye'] > 0) ? round((($dash['cy_paye'] - $dash['ly_paye']) / $dash['ly_paye']) * 100, 1) : 0;
$gross_change = ($dash['ly_gross'] > 0) ? round((($dash['cy_gross'] - $dash['ly_gross']) / $dash['ly_gross']) * 100, 1) : 0;
$srt_change = ($dash['ly_srt'] > 0) ? round((($dash['cy_srt'] - $dash['ly_srt']) / $dash['ly_srt']) * 100, 1) : 0;
$ecal_change = ($dash['ly_ecal'] > 0) ? round((($dash['cy_ecal'] - $dash['ly_ecal']) / $dash['ly_ecal']) * 100, 1) : 0;

// Year progress
$dayOfYear = date('z') + 1;
$daysInYear = date('L') ? 366 : 365;
$yearProgress = round(($dayOfYear / $daysInYear) * 100, 1);
$currentMonth = intval(date('n'));

// Prepare monthly data arrays for chart
$monthLabels = array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
$cyPayeMonthly = array_fill(0, 12, 0);
$lyPayeMonthly = array_fill(0, 12, 0);
$cyGrossMonthly = array_fill(0, 12, 0);
$lyGrossMonthly = array_fill(0, 12, 0);

foreach($dash['monthly_cy'] as $m) { 
    $cyPayeMonthly[intval($m['mth'])-1] = round($m['paye'], 2); 
    $cyGrossMonthly[intval($m['mth'])-1] = round($m['gross'], 2); 
}
foreach($dash['monthly_ly'] as $m) { 
    $lyPayeMonthly[intval($m['mth'])-1] = round($m['paye'], 2); 
    $lyGrossMonthly[intval($m['mth'])-1] = round($m['gross'], 2); 
}

// Effective tax rates
$cy_effective_rate = ($dash['cy_gross'] > 0) ? round(($dash['cy_paye'] / $dash['cy_gross']) * 100, 2) : 0;
$ly_effective_rate = ($dash['ly_gross'] > 0) ? round(($dash['ly_paye'] / $dash['ly_gross']) * 100, 2) : 0;

// Total tax burden (PAYE + SRT + ECAL)
$cy_total_tax = $dash['cy_paye'] + $dash['cy_srt'] + $dash['cy_ecal'];
$ly_total_tax = $dash['ly_paye'] + $dash['ly_srt'] + $dash['ly_ecal'];
?>

<!-- Dashboard Styles -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@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://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<style>
/* ─── PAYE Dashboard Styles ─── */
.paye-wrapper { font-family: 'Poppins', sans-serif; padding: 0; }

.paye-banner {
    background: linear-gradient(135deg, #2AABB3 0%, #187278 100%);
    color: #fff; padding: 28px 32px 20px; border-radius: 12px;
    margin: -10px 0 0 0; position: relative; overflow: hidden;
}
.paye-banner::after {
    content:''; position:absolute; top:-40px; right:-40px;
    width:200px; height:200px; background:rgba(255,255,255,0.06);
    border-radius:50%;
}
.paye-banner h2 { margin:0 0 4px; font-size:22px; font-weight:700; }
.paye-banner .paye-breadcrumb { font-size:13px; opacity:0.85; }
.paye-banner .paye-breadcrumb a { color:#fff; text-decoration:none; }
.paye-banner .paye-year-badge {
    display:inline-block; background:rgba(255,255,255,0.2); padding:4px 14px;
    border-radius:20px; font-size:12px; font-weight:500; margin-top:8px;
}

.paye-toggle-btn {
    display:inline-flex; align-items:center; gap:6px;
    background:#fff; color:#187278; border:none; padding:8px 18px;
    border-radius:8px; cursor:pointer; font-family:'Poppins',sans-serif;
    font-size:13px; font-weight:600; margin-top:12px; transition:all 0.2s;
}
.paye-toggle-btn:hover { background:#E6F7F8; }

.paye-dashboard {
    background:#F8FAFB; border:1px solid #E5E7EB; border-top:none;
    border-radius:0 0 12px 12px; padding:24px; transition:all 0.3s ease;
    overflow:hidden;
}
.paye-dashboard.collapsed { max-height:0; padding:0 24px; border:none; opacity:0; }

/* KPI Cards */
.paye-grid-4 { display:grid; grid-template-columns:repeat(4,1fr); gap:16px; margin-bottom:20px; }
.paye-grid-3 { display:grid; grid-template-columns:repeat(3,1fr); gap:16px; margin-bottom:20px; }
.paye-grid-2 { display:grid; grid-template-columns:repeat(2,1fr); gap:16px; margin-bottom:20px; }

.paye-kpi {
    background:#fff; border-radius:10px; padding:18px 20px;
    border:1px solid #E5E7EB; border-left:4px solid #2AABB3;
    transition: box-shadow 0.2s;
}
.paye-kpi:hover { box-shadow:0 4px 12px rgba(42,171,179,0.12); }
.paye-kpi .kpi-header { display:flex; justify-content:space-between; align-items:flex-start; }
.paye-kpi .kpi-icon {
    width:40px; height:40px; border-radius:10px; display:flex;
    align-items:center; justify-content:center; font-size:18px;
}
.paye-kpi .kpi-icon.teal { background:#E6F7F8; color:#2AABB3; }
.paye-kpi .kpi-icon.green { background:#E8F5E9; color:#52C41A; }
.paye-kpi .kpi-icon.orange { background:#FFF8E1; color:#FAAD14; }
.paye-kpi .kpi-icon.red { background:#FFEBEE; color:#FF4D4F; }
.paye-kpi .kpi-icon.purple { background:#F3E8FF; color:#7C3AED; }
.paye-kpi .kpi-icon.blue { background:#E3F2FD; color:#2196F3; }

.paye-kpi .kpi-value { font-size:22px; font-weight:700; color:#1F2937; margin:10px 0 2px; }
.paye-kpi .kpi-label { font-size:12px; color:#6B7280; font-weight:500; }
.paye-kpi .kpi-compare {
    font-size:11px; margin-top:6px; padding:3px 8px; border-radius:12px;
    display:inline-block; font-weight:600;
}
.paye-kpi .kpi-compare.up { background:#FFF1F0; color:#FF4D4F; }
.paye-kpi .kpi-compare.down { background:#E8F5E9; color:#52C41A; }
.paye-kpi .kpi-compare.neutral { background:#F3F4F6; color:#6B7280; }

.paye-kpi .kpi-sub { font-size:11px; color:#9CA3AF; margin-top:4px; }

/* Year Progress */
.paye-progress-section {
    background:#fff; border-radius:10px; padding:18px 20px;
    border:1px solid #E5E7EB; margin-bottom:20px;
}
.paye-progress-section h4 { margin:0 0 12px; font-size:14px; color:#1F2937; font-weight:600; }
.paye-progress-bar-outer {
    background:#E5E7EB; border-radius:8px; height:24px; position:relative; overflow:hidden;
}
.paye-progress-bar-inner {
    height:100%; border-radius:8px; transition:width 1s ease;
    display:flex; align-items:center; justify-content:center;
    font-size:11px; font-weight:600; color:#fff;
}
.paye-progress-labels { display:flex; justify-content:space-between; margin-top:6px; font-size:11px; color:#6B7280; }

/* Panels */
.paye-panel {
    background:#fff; border-radius:10px; padding:20px;
    border:1px solid #E5E7EB;
}
.paye-panel h4 {
    margin:0 0 16px; font-size:14px; color:#1F2937; font-weight:600;
    display:flex; align-items:center; gap:8px;
}
.paye-panel h4 i { color:#2AABB3; }

/* Chart containers */
.paye-chart-container { position:relative; width:100%; }
.paye-chart-container.bar-chart { height:300px; }
.paye-chart-container.doughnut-chart { height:260px; }

/* Top Contributors Table */
.paye-table { width:100%; border-collapse:collapse; font-size:12px; }
.paye-table th {
    text-align:left; padding:8px 10px; background:#F8FAFB;
    color:#6B7280; font-weight:600; font-size:11px; text-transform:uppercase;
    border-bottom:2px solid #E5E7EB;
}
.paye-table td { padding:8px 10px; border-bottom:1px solid #F3F4F6; color:#1F2937; }
.paye-table tr:hover td { background:#F8FAFB; }
.paye-table .rank-badge {
    width:24px; height:24px; border-radius:50%; display:inline-flex;
    align-items:center; justify-content:center; font-size:11px; font-weight:700;
}
.paye-table .rank-1 { background:#FFD700; color:#fff; }
.paye-table .rank-2 { background:#C0C0C0; color:#fff; }
.paye-table .rank-3 { background:#CD7F32; color:#fff; }
.paye-table .rank-other { background:#E5E7EB; color:#6B7280; }

/* Section Title */
.paye-section-title {
    font-size:13px; color:#6B7280; font-weight:600; text-transform:uppercase;
    letter-spacing:0.5px; margin:24px 0 12px; padding-bottom:8px;
    border-bottom:2px solid #E5E7EB; display:flex; align-items:center; gap:8px;
}
.paye-section-title i { color:#2AABB3; font-size:14px; }

/* Responsive */
@media(max-width:1024px) { .paye-grid-4 { grid-template-columns:repeat(2,1fr); } }
@media(max-width:768px) {
    .paye-grid-4, .paye-grid-3, .paye-grid-2 { grid-template-columns:1fr; }
    .paye-banner { padding:20px; }
    .paye-dashboard { padding:16px; }
}
</style>

<div class="paye-wrapper">

<!-- ═══ Banner ═══ -->
<div class="paye-banner">
    <div class="paye-breadcrumb"><a href="index.php">Home</a> &nbsp;/&nbsp; Payroll &nbsp;/&nbsp; PAYE Tax Report</div>
    <h2><i class="fas fa-file-invoice-dollar"></i> &nbsp;PAYE Tax Deduction Report</h2>
    <div class="paye-year-badge">
        <i class="fas fa-calendar-alt"></i> &nbsp;FY <?php echo $currentYear; ?> &nbsp;|&nbsp; 
        Year Progress: <?php echo $yearProgress; ?>%
    </div>
    <button class="paye-toggle-btn" onclick="togglePayeDash()">
        <i class="fas fa-chart-bar" id="paye-toggle-icon"></i>
        <span id="paye-toggle-text">Hide Dashboard</span>
    </button>
</div>

<!-- ═══ Collapsible Dashboard ═══ -->
<div class="paye-dashboard" id="paye-dashboard">

    <!-- Year Progress Bar -->
    <div class="paye-progress-section">
        <h4><i class="fas fa-hourglass-half" style="color:#FAAD14;"></i> <?php echo $currentYear; ?> Tax Year Progress</h4>
        <div class="paye-progress-bar-outer">
            <div class="paye-progress-bar-inner" style="width:<?php echo $yearProgress; ?>%; background:linear-gradient(90deg,#2AABB3,#187278);">
                <?php echo $yearProgress; ?>% of year complete
            </div>
        </div>
        <div class="paye-progress-labels">
            <span>Jan <?php echo $currentYear; ?></span>
            <span>Month <?php echo $currentMonth; ?> of 12</span>
            <span>Dec <?php echo $currentYear; ?></span>
        </div>
    </div>

    <!-- ─── This Year KPIs ─── -->
    <div class="paye-section-title"><i class="fas fa-chart-line"></i> <?php echo $currentYear; ?> Year-to-Date Summary</div>
    <div class="paye-grid-4">
        <div class="paye-kpi">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Total PAYE Withheld</div>
                    <div class="kpi-value">$<?php echo number_format($dash['cy_paye'], 2); ?></div>
                </div>
                <div class="kpi-icon teal"><i class="fas fa-landmark"></i></div>
            </div>
            <div class="kpi-compare <?php echo ($paye_change > 0) ? 'up' : (($paye_change < 0) ? 'down' : 'neutral'); ?>">
                <i class="fas fa-arrow-<?php echo ($paye_change >= 0) ? 'up' : 'down'; ?>"></i>
                <?php echo abs($paye_change); ?>% vs <?php echo $lastYear; ?>
            </div>
            <div class="kpi-sub">Last Year: $<?php echo number_format($dash['ly_paye'], 2); ?></div>
        </div>

        <div class="paye-kpi" style="border-left-color:#52C41A;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Total Gross Earnings</div>
                    <div class="kpi-value">$<?php echo number_format($dash['cy_gross'], 2); ?></div>
                </div>
                <div class="kpi-icon green"><i class="fas fa-dollar-sign"></i></div>
            </div>
            <div class="kpi-compare <?php echo ($gross_change > 0) ? 'up' : (($gross_change < 0) ? 'down' : 'neutral'); ?>">
                <i class="fas fa-arrow-<?php echo ($gross_change >= 0) ? 'up' : 'down'; ?>"></i>
                <?php echo abs($gross_change); ?>% vs <?php echo $lastYear; ?>
            </div>
            <div class="kpi-sub">Last Year: $<?php echo number_format($dash['ly_gross'], 2); ?></div>
        </div>

        <div class="paye-kpi" style="border-left-color:#FAAD14;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Total SRT Withheld</div>
                    <div class="kpi-value">$<?php echo number_format($dash['cy_srt'], 2); ?></div>
                </div>
                <div class="kpi-icon orange"><i class="fas fa-percentage"></i></div>
            </div>
            <div class="kpi-compare <?php echo ($srt_change > 0) ? 'up' : (($srt_change < 0) ? 'down' : 'neutral'); ?>">
                <i class="fas fa-arrow-<?php echo ($srt_change >= 0) ? 'up' : 'down'; ?>"></i>
                <?php echo abs($srt_change); ?>% vs <?php echo $lastYear; ?>
            </div>
            <div class="kpi-sub">Last Year: $<?php echo number_format($dash['ly_srt'], 2); ?></div>
        </div>

        <div class="paye-kpi" style="border-left-color:#FF4D4F;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Total ECAL Withheld</div>
                    <div class="kpi-value">$<?php echo number_format($dash['cy_ecal'], 2); ?></div>
                </div>
                <div class="kpi-icon red"><i class="fas fa-hand-holding-usd"></i></div>
            </div>
            <div class="kpi-compare <?php echo ($ecal_change > 0) ? 'up' : (($ecal_change < 0) ? 'down' : 'neutral'); ?>">
                <i class="fas fa-arrow-<?php echo ($ecal_change >= 0) ? 'up' : 'down'; ?>"></i>
                <?php echo abs($ecal_change); ?>% vs <?php echo $lastYear; ?>
            </div>
            <div class="kpi-sub">Last Year: $<?php echo number_format($dash['ly_ecal'], 2); ?></div>
        </div>
    </div>

    <!-- ─── Rate & Employee KPIs ─── -->
    <div class="paye-grid-4">
        <div class="paye-kpi" style="border-left-color:#7C3AED;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Effective Tax Rate</div>
                    <div class="kpi-value"><?php echo $cy_effective_rate; ?>%</div>
                </div>
                <div class="kpi-icon purple"><i class="fas fa-chart-pie"></i></div>
            </div>
            <div class="kpi-sub">Last Year: <?php echo $ly_effective_rate; ?>%</div>
        </div>

        <div class="paye-kpi" style="border-left-color:#2196F3;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Employees (This Year)</div>
                    <div class="kpi-value"><?php echo number_format($dash['cy_employees']); ?></div>
                </div>
                <div class="kpi-icon blue"><i class="fas fa-users"></i></div>
            </div>
            <div class="kpi-sub">Last Year: <?php echo number_format($dash['ly_employees']); ?></div>
        </div>

        <div class="paye-kpi" style="border-left-color:#2AABB3;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Total Tax Burden (<?php echo $currentYear; ?>)</div>
                    <div class="kpi-value">$<?php echo number_format($cy_total_tax, 2); ?></div>
                </div>
                <div class="kpi-icon teal"><i class="fas fa-coins"></i></div>
            </div>
            <div class="kpi-sub">PAYE + SRT + ECAL combined</div>
        </div>

        <div class="paye-kpi" style="border-left-color:#6B7280;">
            <div class="kpi-header">
                <div>
                    <div class="kpi-label">Total Tax Burden (<?php echo $lastYear; ?>)</div>
                    <div class="kpi-value">$<?php echo number_format($ly_total_tax, 2); ?></div>
                </div>
                <div class="kpi-icon" style="background:#F3F4F6;color:#6B7280;"><i class="fas fa-history"></i></div>
            </div>
            <div class="kpi-sub">Prior year comparison</div>
        </div>
    </div>

    <!-- ─── Charts Row ─── -->
    <div class="paye-section-title"><i class="fas fa-chart-bar"></i> Monthly Trends &amp; Breakdown</div>
    <div class="paye-grid-2">
        <!-- Monthly PAYE Comparison Chart -->
        <div class="paye-panel">
            <h4><i class="fas fa-chart-bar"></i> Monthly PAYE: <?php echo $currentYear; ?> vs <?php echo $lastYear; ?></h4>
            <div class="paye-chart-container bar-chart">
                <canvas id="payeMonthlyChart"></canvas>
            </div>
        </div>

        <!-- Tax Type Breakdown Doughnut -->
        <div class="paye-panel">
            <h4><i class="fas fa-chart-pie"></i> Tax Composition — <?php echo $currentYear; ?></h4>
            <div class="paye-chart-container doughnut-chart">
                <canvas id="payeTaxBreakdown"></canvas>
            </div>
        </div>
    </div>

    <!-- Monthly Gross Comparison -->
    <div class="paye-grid-2" style="margin-top:16px;">
        <div class="paye-panel">
            <h4><i class="fas fa-chart-area"></i> Monthly Gross Earnings: <?php echo $currentYear; ?> vs <?php echo $lastYear; ?></h4>
            <div class="paye-chart-container bar-chart">
                <canvas id="payeGrossChart"></canvas>
            </div>
        </div>

        <!-- Top PAYE Contributors -->
        <div class="paye-panel">
            <h4><i class="fas fa-trophy"></i> Top 10 PAYE Contributors — <?php echo $currentYear; ?></h4>
            <div style="overflow-x:auto; max-height:300px; overflow-y:auto;">
                <table class="paye-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Employee</th>
                            <th>Department</th>
                            <th style="text-align:right;">PAYE</th>
                            <th style="text-align:right;">Gross</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $rank = 0;
                    foreach($dash['top_paye'] as $tp) {
                        $rank++;
                        $rankClass = ($rank <= 3) ? 'rank-'.$rank : 'rank-other';
                        echo '<tr>';
                        echo '<td><span class="rank-badge '.$rankClass.'">'.$rank.'</span></td>';
                        echo '<td>'.htmlspecialchars($tp['full_name']).'</td>';
                        echo '<td>'.htmlspecialchars(isset($tp['departmentname']) ? $tp['departmentname'] : '-').'</td>';
                        echo '<td style="text-align:right;font-weight:600;">$'.number_format($tp['total_paye'],2).'</td>';
                        echo '<td style="text-align:right;">$'.number_format($tp['total_gross'],2).'</td>';
                        echo '</tr>';
                    }
                    if($rank == 0) { echo '<tr><td colspan="5" style="text-align:center;color:#9CA3AF;">No data available</td></tr>'; }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <?php if(count($dash['dept_breakdown']) > 0): ?>
    <!-- Department Breakdown -->
    <div class="paye-grid-2" style="margin-top:16px;">
        <div class="paye-panel">
            <h4><i class="fas fa-building"></i> PAYE by Department — <?php echo $currentYear; ?></h4>
            <div class="paye-chart-container bar-chart">
                <canvas id="payeDeptChart"></canvas>
            </div>
        </div>
        <div class="paye-panel">
            <h4><i class="fas fa-list-alt"></i> Department Summary</h4>
            <div style="overflow-x:auto; max-height:300px; overflow-y:auto;">
                <table class="paye-table">
                    <thead>
                        <tr>
                            <th>Department</th>
                            <th style="text-align:center;">Staff</th>
                            <th style="text-align:right;">PAYE</th>
                            <th style="text-align:right;">Gross</th>
                            <th style="text-align:right;">Rate</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach($dash['dept_breakdown'] as $db_row):
                        $dept_rate = ($db_row['total_gross'] > 0) ? round(($db_row['total_paye'] / $db_row['total_gross']) * 100, 1) : 0;
                    ?>
                        <tr>
                            <td style="font-weight:500;"><?php echo htmlspecialchars($db_row['dept']); ?></td>
                            <td style="text-align:center;"><?php echo $db_row['emp_count']; ?></td>
                            <td style="text-align:right;font-weight:600;">$<?php echo number_format($db_row['total_paye'],2); ?></td>
                            <td style="text-align:right;">$<?php echo number_format($db_row['total_gross'],2); ?></td>
                            <td style="text-align:right;"><?php echo $dept_rate; ?>%</td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>

</div><!-- end dashboard -->

<!-- ═══ Chart.js Initialization ═══ -->
<script>
document.addEventListener('DOMContentLoaded', function(){
    var monthLabels = <?php echo json_encode($monthLabels); ?>;
    var cyPaye = <?php echo json_encode($cyPayeMonthly); ?>;
    var lyPaye = <?php echo json_encode($lyPayeMonthly); ?>;
    var cyGross = <?php echo json_encode($cyGrossMonthly); ?>;
    var lyGross = <?php echo json_encode($lyGrossMonthly); ?>;
    var currentMonth = <?php echo $currentMonth; ?>;

    var teal = '#2AABB3', tealLight = 'rgba(42,171,179,0.15)';
    var grey = '#9CA3AF', greyLight = 'rgba(156,163,175,0.15)';

    var tooltipCurrency = {
        callbacks: {
            label: function(ctx) {
                return ctx.dataset.label + ': $' + ctx.parsed.y.toLocaleString(undefined,{minimumFractionDigits:2});
            }
        }
    };

    // Monthly PAYE Chart
    new Chart(document.getElementById('payeMonthlyChart'), {
        type: 'bar',
        data: {
            labels: monthLabels.slice(0, Math.max(currentMonth, 1)),
            datasets: [
                { label: '<?php echo $currentYear; ?> PAYE', data: cyPaye.slice(0, Math.max(currentMonth, 1)), backgroundColor: teal, borderRadius: 4 },
                { label: '<?php echo $lastYear; ?> PAYE', data: lyPaye.slice(0, Math.max(currentMonth, 1)), backgroundColor: grey, borderRadius: 4 }
            ]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            plugins: { legend: { position:'top', labels:{font:{family:'Poppins',size:11}} }, tooltip: tooltipCurrency },
            scales: {
                y: { beginAtZero:true, ticks:{ callback:function(v){return '$'+v.toLocaleString();}, font:{size:10} }, grid:{color:'#F3F4F6'} },
                x: { grid:{display:false}, ticks:{font:{size:10}} }
            }
        }
    });

    // Tax Breakdown Doughnut
    new Chart(document.getElementById('payeTaxBreakdown'), {
        type: 'doughnut',
        data: {
            labels: ['PAYE','SRT','ECAL'],
            datasets: [{
                data: [<?php echo $dash['cy_paye']; ?>, <?php echo $dash['cy_srt']; ?>, <?php echo $dash['cy_ecal']; ?>],
                backgroundColor: ['#2AABB3','#FAAD14','#FF4D4F'],
                borderWidth: 2, borderColor: '#fff'
            }]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            cutout: '60%',
            plugins: {
                legend: { position:'bottom', labels:{font:{family:'Poppins',size:11}, padding:16} },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            var total = ctx.dataset.data.reduce(function(a,b){return a+b;},0);
                            var pct = total > 0 ? ((ctx.parsed / total)*100).toFixed(1) : 0;
                            return ctx.label + ': $' + ctx.parsed.toLocaleString(undefined,{minimumFractionDigits:2}) + ' (' + pct + '%)';
                        }
                    }
                }
            }
        }
    });

    // Monthly Gross Chart
    new Chart(document.getElementById('payeGrossChart'), {
        type: 'bar',
        data: {
            labels: monthLabels.slice(0, Math.max(currentMonth, 1)),
            datasets: [
                { label: '<?php echo $currentYear; ?> Gross', data: cyGross.slice(0, Math.max(currentMonth, 1)), backgroundColor: '#52C41A', borderRadius: 4 },
                { label: '<?php echo $lastYear; ?> Gross', data: lyGross.slice(0, Math.max(currentMonth, 1)), backgroundColor: 'rgba(82,196,26,0.3)', borderRadius: 4 }
            ]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            plugins: { legend: { position:'top', labels:{font:{family:'Poppins',size:11}} }, tooltip: tooltipCurrency },
            scales: {
                y: { beginAtZero:true, ticks:{ callback:function(v){return '$'+v.toLocaleString();}, font:{size:10} }, grid:{color:'#F3F4F6'} },
                x: { grid:{display:false}, ticks:{font:{size:10}} }
            }
        }
    });

    <?php if(count($dash['dept_breakdown']) > 0): ?>
    // Department Chart
    var deptLabels = <?php echo json_encode(array_map(function($d){return $d['dept'];}, $dash['dept_breakdown'])); ?>;
    var deptPaye = <?php echo json_encode(array_map(function($d){return round($d['total_paye'],2);}, $dash['dept_breakdown'])); ?>;
    var deptColors = ['#2AABB3','#1E8F96','#187278','#52C41A','#FAAD14','#FF4D4F','#7C3AED','#2196F3','#FF9800','#607D8B'];

    new Chart(document.getElementById('payeDeptChart'), {
        type: 'bar',
        data: {
            labels: deptLabels,
            datasets: [{
                label: 'PAYE by Dept',
                data: deptPaye,
                backgroundColor: deptColors.slice(0, deptLabels.length),
                borderRadius: 4
            }]
        },
        options: {
            indexAxis: 'y', responsive: true, maintainAspectRatio: false,
            plugins: { legend:{display:false}, tooltip: tooltipCurrency },
            scales: {
                x: { beginAtZero:true, ticks:{callback:function(v){return '$'+v.toLocaleString();}, font:{size:10}}, grid:{color:'#F3F4F6'} },
                y: { ticks:{font:{size:10,family:'Poppins'}}, grid:{display:false} }
            }
        }
    });
    <?php endif; ?>

    // Remove loading modal
    var lm = document.getElementById('paye-loading-modal');
    if(lm) { lm.style.transition='opacity 0.4s'; lm.style.opacity='0'; setTimeout(function(){ lm.remove(); }, 400); }
    clearInterval(_payeTimer);
});

// Toggle dashboard
function togglePayeDash(){
    var d = document.getElementById('paye-dashboard');
    var t = document.getElementById('paye-toggle-text');
    var i = document.getElementById('paye-toggle-icon');
    if(d.classList.contains('collapsed')){
        d.classList.remove('collapsed');
        d.style.maxHeight = d.scrollHeight + 'px';
        t.textContent = 'Hide Dashboard';
        i.className = 'fas fa-chart-bar';
        localStorage.setItem('paye_dash_state','open');
    } else {
        d.classList.add('collapsed');
        d.style.maxHeight = '0';
        t.textContent = 'Show Dashboard';
        i.className = 'fas fa-chevron-down';
        localStorage.setItem('paye_dash_state','closed');
    }
}
// Restore state
(function(){
    var s = localStorage.getItem('paye_dash_state');
    if(s === 'closed'){
        var d = document.getElementById('paye-dashboard');
        var t = document.getElementById('paye-toggle-text');
        var i = document.getElementById('paye-toggle-icon');
        if(d){ d.classList.add('collapsed'); d.style.maxHeight='0'; }
        if(t) t.textContent = 'Show Dashboard';
        if(i) i.className = 'fas fa-chevron-down';
    }
})();
</script>

<br/>

<!-- ═══ Original Report Form & Table Below ═══ -->
<?php

$userid = isset($_SESSION['UserID']) ? $_SESSION['UserID'] : '';
if ($userid == 'admin' || $userid == 'jprasad' || $userid == 'sharukh' || $userid == 'mkhan') {

    if (isset($_POST['quote'])) {

        $fromid = intval($_POST['fromdate']);
        $toid   = intval($_POST['todate']);

        // Pre-fetch previous YTD values for each employee (from the record just BEFORE current range)
        $prev_ytd_map = array();
        $sql = "
            SELECT pd.employeeid, pd.ytd_gross, pd.ytd_income_tax_withheld
            FROM payrun_details pd
            INNER JOIN (
                SELECT employeeid, MAX(id) as maxid
                FROM payrun_details
                WHERE id < $fromid
                GROUP BY employeeid
            ) t2 ON pd.employeeid = t2.employeeid AND pd.id = t2.maxid
        ";
        $res = DB_query($sql);
        while ($r = DB_fetch_array($res)) {
            $prev_ytd_map[$r['employeeid']] = array(
                'ytd_gross' => $r['ytd_gross'],
                'ytd_income_tax_withheld' => $r['ytd_income_tax_withheld']
            );
        }

        // Output HTML (with DataTables)
        ?>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css"/>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css"/>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>

        <div class="table-responsive">
        <table id="projectreport" class="display nowrap" style="width:100%">
        <thead>
            <tr class="info">
                <th><?php echo _('TIN'); ?></th>
                <th><?php echo _('Employee ID'); ?></th>
                <th><?php echo _('First Name'); ?></th>
                <th><?php echo _('Middle Name'); ?></th>
                <th><?php echo _('Last Name'); ?></th>
                <th><?php echo _('P or S'); ?></th>
                <th><?php echo _('Start Date'); ?></th>
                <th><?php echo _('Finish Date'); ?></th>
                <th><?php echo _('Gross'); ?></th>
                <th><?php echo _('PAYE'); ?></th>
                <th><?php echo _('SRT'); ?></th>
                <th><?php echo _('ECAL'); ?></th>
                <th><?php echo _('DOB'); ?></th>
                <th><?php echo _('YTD-GROSS-New'); ?></th>
                <th><?php echo _('YTD-PAYE'); ?></th>
            </tr>
        </thead>
        <tbody>
        <?php
        $grandtotal = 0;

        $querypayrun = "
            SELECT 
                payrun_details.employeeid, employeemaster.tin, employeemaster.first_name, employeemaster.middle_name,
                employeemaster.last_name, employeemaster.employment_type, employeemaster.start_date, employeemaster.finish_date, 
                employeemaster.date_of_birth,
                SUM(payrun_details.income_tax_to_withhold) as totalpaye,
                SUM(payrun_details.totalgross_amount) as totalgrossformonth,
                SUM(payrun_details.srt_tax_to_withhold) as totalsrt,
                SUM(payrun_details.ecal_tax_to_withhold) as totalecal
            FROM payrun_details
            INNER JOIN calendar_management ON payrun_details.id = calendar_management.id
            INNER JOIN employeemaster ON payrun_details.employeeid = employeemaster.employeeid
            WHERE payrun_details.id BETWEEN $fromid AND $toid
            GROUP BY payrun_details.employeeid
        ";
        $resultpayrun = DB_query($querypayrun);

        while ($myrowpayrun = DB_fetch_array($resultpayrun)) {

            $employmenttype = '';
            if (isset($myrowpayrun['employment_type']) && $myrowpayrun['employment_type'] == 'Primary') {
                $employmenttype = 'P';
            } elseif (isset($myrowpayrun['employment_type']) && $myrowpayrun['employment_type'] == 'Secondary') {
                $employmenttype = 'S';
            }

            $sdate = (!empty($myrowpayrun['start_date']) && $myrowpayrun['start_date'] != '0000-00-00') ?
                date("d/m/y", strtotime($myrowpayrun['start_date'])) : '';
            $fdate = (!empty($myrowpayrun['finish_date']) && $myrowpayrun['finish_date'] != '0000-00-00') ?
                date("d/m/y", strtotime($myrowpayrun['finish_date'])) : '';
            if ($fdate == '30/11/-1') $fdate = '';
            $dateofbirth = (!empty($myrowpayrun['date_of_birth']) && $myrowpayrun['date_of_birth'] != '0000-00-00') ?
                date("d/m/y", strtotime($myrowpayrun['date_of_birth'])) : '';

            // Get previous YTD values
            $prev_ytd_gross = isset($prev_ytd_map[$myrowpayrun['employeeid']]) ? $prev_ytd_map[$myrowpayrun['employeeid']]['ytd_gross'] : '';
            $prev_ytd_income_tax_withheld = isset($prev_ytd_map[$myrowpayrun['employeeid']]) ? $prev_ytd_map[$myrowpayrun['employeeid']]['ytd_income_tax_withheld'] : '';

            ?>
            <tr>
                <td><?php echo $myrowpayrun['tin']; ?></td>
                <td><?php echo $myrowpayrun['employeeid']; ?></td>
                <td><?php echo $myrowpayrun['first_name']; ?></td>
                <td><?php echo $myrowpayrun['middle_name']; ?></td>
                <td><?php echo $myrowpayrun['last_name']; ?></td>
                <td><?php echo $employmenttype; ?></td>
                <td><?php echo $sdate; ?></td>
                <td><?php echo $fdate; ?></td>
                <td><?php echo $myrowpayrun['totalgrossformonth']; ?></td>
                <td><?php echo $myrowpayrun['totalpaye']; ?></td>
                <td><?php echo $myrowpayrun['totalsrt']; ?></td>
                <td><?php echo $myrowpayrun['totalecal']; ?></td>
                <td><?php echo $dateofbirth; ?></td>
                <td><?php echo $prev_ytd_gross; ?></td>
                <td><?php echo $prev_ytd_income_tax_withheld; ?></td>
            </tr>
            <?php
            $grandtotal += $myrowpayrun['totalpaye'];
        }
        ?>
        </tbody>
        <tfoot>
            <tr>
                <td><b>Grand Total PAYE Amount:</b></td>
                <td colspan="8"></td>
                <td><b><?php echo round($grandtotal, 2); ?></b></td>
                <td colspan="5"></td>
            </tr>
        </tfoot>
        </table>
        </div>
        <script>
        $(document).ready(function() {
           $('#projectreport').DataTable( {
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'pdfHtml5',
                        orientation: 'landscape',
                        pageSize: 'A3',
                        customize: function(doc) {
                            doc.defaultStyle.fontSize = 10;
                        }
                    },
                    {
                        extend: 'excelHtml5'
                    },
                    {
                        extend: 'copyHtml5'
                    }
                ]
            } );
        });
        </script>
        <?php

    } else {
        // Show form
        echo '<div style="background:#fff;border-radius:10px;padding:24px;border:1px solid #E5E7EB;margin-top:8px;">';
        echo '<h4 style="font-family:Poppins,sans-serif;color:#1F2937;margin:0 0 16px;font-size:16px;"><i class="fas fa-filter" style="color:#2AABB3;"></i> &nbsp;Generate PAYE Report</h4>';
        echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '">';
        echo '<p style="font-family:Poppins,sans-serif;color:#6B7280;font-size:13px;margin:0 0 16px;">PAYE General Report for in-house use only</p>';

        date_default_timezone_set('Pacific/Fiji');
        $date = date('Y-m-d H:i:s');

        echo '<div class="col-sm-10">';
        echo '<input type="hidden" name="FormID" value="' . (isset($_SESSION['FormID']) ? $_SESSION['FormID'] : '') . '" />';
        echo '<table class="table"><tr>';
        ?>
        <td>Select From Weekending Period </td>
        <td><select name="fromdate" required style="padding:6px 12px;border:1px solid #D1D5DB;border-radius:6px;font-family:Poppins,sans-serif;font-size:13px;">
            <?php
            $SQL = "SELECT * FROM calendar_management order by id desc";
            $result = DB_query($SQL);
            while ($myrow = DB_fetch_array($result)) {
                echo '<option value="' . $myrow['id'] . '">' . $myrow['id'] . ' - ' . $myrow['end_date'] . '</option>';
            }
            ?>
            </select>
        </td></tr>
        <tr>
        <td>Select To Weekending Period </td>
        <td><select name="todate" required style="padding:6px 12px;border:1px solid #D1D5DB;border-radius:6px;font-family:Poppins,sans-serif;font-size:13px;">
            <?php
            $result = DB_query($SQL);
            while ($myrow = DB_fetch_array($result)) {
                echo '<option value="' . $myrow['id'] . '">' . $myrow['id'] . ' - ' . $myrow['end_date'] . '</option>';
            }
            ?>
            </select>
        </td></tr>
        <?php
        echo '<tr><td colspan="2" style="padding-top:12px;"><input type="submit" name="quote" value="' . _('Show report') . '" style="background:linear-gradient(135deg,#2AABB3,#187278);color:#fff;border:none;padding:10px 28px;border-radius:8px;font-family:Poppins,sans-serif;font-size:14px;font-weight:600;cursor:pointer;" /></td></tr>';
        echo '</table></div>';
        echo '</form>';
        echo '</div>';
    }

} else {
    echo '<div style="background:#FFF1F0;border:1px solid #FF4D4F;border-radius:10px;padding:20px;margin-top:16px;font-family:Poppins,sans-serif;color:#FF4D4F;">';
    echo '<i class="fas fa-lock"></i> &nbsp;Not authorized to view this section';
    echo '</div>';
}
?>

</div><!-- end paye-wrapper -->

<?php
echo '</div>';
?>
                        
                    </div>
                </div>
            </div>
                        
                        

                            <!--end:: Widgets/Stats-->

                            <!--Begin::Section-->
                            

        <!-- end::Quick Sidebar -->

        <!-- begin::Scroll Top -->
        <div id="m_scroll_top" class="m-scroll-top">
            <i class="la la-arrow-up"></i>
        </div>

        <!-- end::Scroll Top -->

        <!-- begin::Quick Nav -->
        

        <!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

        <!--end::Page Scripts -->
    </body>

    <!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
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'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
    $_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">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
        $NoEntries = true;
        if ($ReportList) {
            foreach ($ReportList as $Report) {
                if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
                    $RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
                    $RptLinks .= '</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">';
                    $RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
                    $RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
                    $RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
                    $RptLinks .= '</li>';
                    $NoForms = false;
                    $NoEntries = false;
                }
            }
        }
        if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
    }
    return $RptLinks;
}
    
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>



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