<?php
/* Enhanced Fixed Deductions Page - OPTIMIZED */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP-Fixed Deductions');
include('includes/newheader.php');

/* ── Loading Modal (flush first) ── */
?>
<div id="fd-loading-modal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.92);z-index:99999;display:flex;align-items:center;justify-content:center;flex-direction:column;">
    <div style="text-align:center;">
        <div style="width:44px;height:44px;border:4px solid #E6F7F8;border-top:4px solid #2AABB3;border-radius:50%;animation:fd-spin 0.8s linear infinite;margin:0 auto 14px;"></div>
        <div style="font-family:'Poppins',sans-serif;font-size:14px;color:#1F2937;font-weight:500;">Loading Fixed Deductions...</div>
        <div id="fd-load-timer" style="font-family:'Poppins',sans-serif;font-size:12px;color:#6B7280;margin-top:4px;">0s</div>
    </div>
</div>
<style>@keyframes fd-spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style>
<script>(function(){var s=0,el=document.getElementById('fd-load-timer');window._fdT=setInterval(function(){s++;if(el)el.textContent=s+'s';},1000);})();</script>
<?php if(ob_get_level()) ob_flush(); flush(); ?>

<?php
/* ══════════════════════════════════════════════
   OPTIMIZED QUERIES — 4 queries total
   (was 8 separate queries before)
   ══════════════════════════════════════════════ */
$dbHost='localhost'; $dbUser='sooggoo'; $dbPass='4Compassion*'; $dbName='evergreenint';
$dbc = new mysqli($dbHost,$dbUser,$dbPass,$dbName);
if($dbc->connect_error) $dbc=null;

$totalDeductions=0; $pendingCount=0; $completedCount=0; $cancelledCount=0;
$totalAmountPending=0; $totalAmountCompleted=0; $totalDeductionAmount=0;
$byCategory=array(); $byDepartment=array(); $byPayCycle=array();
$recentDeductions=array(); $highValueAlerts=array(); $topEmployees=array();

if($dbc){

    /* ── Q1: Status summary → all KPIs from 1 query ── */
    $r = $dbc->query("SELECT status, COUNT(*) as cnt,
        IFNULL(SUM(total_amount_to_deduct),0) as total_amt,
        IFNULL(SUM(deduction_amount),0) as ded_amt
        FROM fixeddeductions GROUP BY status");
    if($r){
        while($row=$r->fetch_assoc()){
            $st = strtolower(trim(isset($row['status']) ? $row['status'] : ''));
            $c = intval($row['cnt']);
            $totalDeductions += $c;
            if($st=='pending'){
                $pendingCount=$c;
                $totalAmountPending=floatval($row['total_amt']);
                $totalDeductionAmount=floatval($row['ded_amt']);
            }
            if($st=='completed'){ $completedCount=$c; $totalAmountCompleted=floatval($row['total_amt']); }
            if($st=='cancelled'){ $cancelledCount=$c; }
        }
        $r->free();
    }

    /* ── Q2: Chart data — 3 small GROUP BY queries (no heavy JOINs) ── */
    // Category top 6
    $r = $dbc->query("SELECT c.name as label, COUNT(*) as cnt,
        IFNULL(SUM(f.total_amount_to_deduct),0) as amt
        FROM fixeddeductions f
        LEFT JOIN fixed_deduction_codecategory c ON f.name=c.id
        GROUP BY f.name ORDER BY cnt DESC LIMIT 6");
    if($r){
        while($row=$r->fetch_assoc()){
            $byCategory[] = array(
                'name' => (isset($row['label']) && $row['label']) ? $row['label'] : 'Unknown',
                'count' => intval($row['cnt']),
                'amount' => floatval($row['amt'])
            );
        }
        $r->free();
    }

    // Department top 6 (pending only)
    $r = $dbc->query("SELECT d.departmentname as label, COUNT(*) as cnt,
        IFNULL(SUM(f.total_amount_to_deduct),0) as amt
        FROM fixeddeductions f
        LEFT JOIN department d ON f.department=d.departmentid
        WHERE f.status='pending'
        GROUP BY f.department ORDER BY amt DESC LIMIT 6");
    if($r){
        while($row=$r->fetch_assoc()){
            $byDepartment[] = array(
                'name' => (isset($row['label']) && $row['label']) ? $row['label'] : 'Unassigned',
                'count' => intval($row['cnt']),
                'amount' => floatval($row['amt'])
            );
        }
        $r->free();
    }

    // Pay cycle (pending only — tiny result set)
    $r = $dbc->query("SELECT pay_cycle, COUNT(*) as cnt,
        IFNULL(SUM(deduction_amount),0) as amt
        FROM fixeddeductions WHERE status='pending' GROUP BY pay_cycle");
    if($r){
        while($row=$r->fetch_assoc()){
            $pc = (isset($row['pay_cycle']) && $row['pay_cycle']) ? $row['pay_cycle'] : 'Not Set';
            $byPayCycle[] = array('cycle'=>$pc, 'count'=>intval($row['cnt']), 'amount'=>floatval($row['amt']));
        }
        $r->free();
    }

    /* ── Q3: Recent 15 → split into recent list + high-value alerts in PHP ── */
    $r = $dbc->query("SELECT f.id, e.first_name, e.last_name, c.name as category_name,
        f.deduction_amount, f.total_amount_to_deduct, f.status, f.pay_cycle, f.estimate_cycle
        FROM fixeddeductions f
        LEFT JOIN employeemaster e ON f.employeeid=e.employeeid
        LEFT JOIN fixed_deduction_codecategory c ON f.name=c.id
        ORDER BY f.id DESC LIMIT 15");
    if($r){
        while($row=$r->fetch_assoc()){
            if(count($recentDeductions) < 8) $recentDeductions[] = $row;
            $st2 = strtolower(trim(isset($row['status']) ? $row['status'] : ''));
            if($st2=='pending' && floatval($row['total_amount_to_deduct']) > 1000 && count($highValueAlerts) < 5){
                $highValueAlerts[] = $row;
            }
        }
        $r->free();
    }

    /* ── Q4: Top employees by pending amount ── */
    $r = $dbc->query("SELECT e.first_name, e.last_name, COUNT(*) as ded_count,
        IFNULL(SUM(f.total_amount_to_deduct),0) as total_amt,
        IFNULL(SUM(f.deduction_amount),0) as per_cycle
        FROM fixeddeductions f
        LEFT JOIN employeemaster e ON f.employeeid=e.employeeid
        WHERE f.status='pending'
        GROUP BY f.employeeid ORDER BY total_amt DESC LIMIT 6");
    if($r){
        while($row=$r->fetch_assoc()) $topEmployees[] = $row;
        $r->free();
    }

    $dbc->close();
}

$byCategoryJSON  = json_encode($byCategory);
$byDepartmentJSON = json_encode($byDepartment);
$byPayCycleJSON  = json_encode($byPayCycle);
$recentJSON      = json_encode($recentDeductions);
$highValueJSON   = json_encode($highValueAlerts);
$topEmployeesJSON = json_encode($topEmployees);
?>

<!-- Chart.js + Icons -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>

<style>
.fd-page *{box-sizing:border-box;font-family:'Poppins',sans-serif;}

/* Banner */
.fd-banner{background:linear-gradient(135deg,#2AABB3 0%,#1E8F96 50%,#187278 100%);border-radius:12px;padding:24px 28px;margin:0 0 20px 0;color:#fff;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;}
.fd-banner h1{font-size:20px;font-weight:700;margin:0 0 3px 0;color:#fff;}
.fd-breadcrumb{font-size:12px;opacity:0.85;display:flex;align-items:center;gap:5px;}
.fd-breadcrumb a{color:#fff;text-decoration:none;opacity:0.8;}
.fd-breadcrumb a:hover{opacity:1;}
.fd-banner-btn{background:rgba(255,255,255,0.18);border:1px solid rgba(255,255,255,0.25);color:#fff;border-radius:8px;padding:7px 14px;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s;display:inline-flex;align-items:center;gap:5px;}
.fd-banner-btn:hover{background:rgba(255,255,255,0.28);}

/* Toggle */
.fd-dash-toggle{display:flex;align-items:center;gap:7px;padding:8px 0;margin-bottom:6px;cursor:pointer;font-size:13px;font-weight:600;color:#1F2937;user-select:none;}
.fd-dash-toggle i{color:#2AABB3;transition:transform 0.3s;font-size:11px;}
.fd-dash-toggle.collapsed i{transform:rotate(-90deg);}

/* KPIs */
.fd-kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px;}
.fd-kpi-card{background:#fff;border-radius:10px;padding:16px 18px;border:1px solid #E5E7EB;border-left:4px solid #2AABB3;display:flex;align-items:center;gap:12px;transition:box-shadow 0.2s;}
.fd-kpi-card:hover{box-shadow:0 3px 10px rgba(42,171,179,0.1);}
.fd-kpi-card.warning{border-left-color:#FAAD14;}
.fd-kpi-card.success{border-left-color:#52C41A;}
.fd-kpi-card.danger{border-left-color:#FF4D4F;}
.fd-kpi-card.info{border-left-color:#1890FF;}
.fd-kpi-icon{width:40px;height:40px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0;}
.fd-kpi-icon.primary{background:#E6F7F8;color:#2AABB3;}
.fd-kpi-icon.warning{background:#FFF8E6;color:#FAAD14;}
.fd-kpi-icon.success{background:#E8F8E8;color:#52C41A;}
.fd-kpi-icon.danger{background:#FFE8E8;color:#FF4D4F;}
.fd-kpi-icon.info{background:#E6F0FF;color:#1890FF;}
.fd-kpi-value{font-size:20px;font-weight:700;color:#1F2937;line-height:1.2;}
.fd-kpi-label{font-size:11px;color:#6B7280;font-weight:500;margin-top:1px;}

/* ── Charts — FIXED 200px height wrapper ── */
.fd-chart-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-bottom:20px;}
.fd-chart-card{background:#fff;border-radius:10px;border:1px solid #E5E7EB;padding:16px 18px;}
.fd-chart-title{font-size:13px;font-weight:600;color:#1F2937;margin:0 0 12px 0;display:flex;align-items:center;gap:7px;}
.fd-chart-title i{color:#2AABB3;font-size:13px;}
.fd-chart-wrap{position:relative;width:100%;height:200px;max-height:200px;overflow:hidden;}

/* Panels */
.fd-panel-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-bottom:20px;}
.fd-panel-card{background:#fff;border-radius:10px;border:1px solid #E5E7EB;padding:16px 18px;max-height:310px;overflow-y:auto;}
.fd-panel-card::-webkit-scrollbar{width:4px;}
.fd-panel-card::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:4px;}
.fd-panel-title{font-size:13px;font-weight:600;color:#1F2937;margin:0 0 10px 0;display:flex;align-items:center;gap:7px;}
.fd-panel-title i{color:#2AABB3;}
.fd-list-row{display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid #F3F4F6;gap:8px;}
.fd-list-row:last-child{border-bottom:none;}
.fd-list-name{font-size:12px;color:#1F2937;font-weight:500;}
.fd-list-sub{font-size:11px;color:#6B7280;}
.fd-list-amount{font-size:12px;font-weight:600;color:#1F2937;text-align:right;white-space:nowrap;}
.fd-status-badge{display:inline-block;padding:1px 8px;border-radius:10px;font-size:10px;font-weight:600;text-transform:capitalize;}
.fd-status-badge.pending{background:#FFF8E6;color:#D48806;}
.fd-status-badge.completed{background:#E8F8E8;color:#389E0D;}
.fd-status-badge.cancelled{background:#FFE8E8;color:#CF1322;}

/* Alerts */
.fd-alert-row{display:flex;align-items:center;gap:8px;padding:8px 10px;background:#FFFBF0;border:1px solid #FFE58F;border-radius:7px;margin-bottom:6px;font-size:12px;color:#1F2937;}
.fd-alert-row i{color:#FAAD14;font-size:13px;flex-shrink:0;}
.fd-alert-amt{font-weight:700;color:#D48806;margin-left:auto;white-space:nowrap;}

/* Progress */
.fd-progress-wrap{display:flex;align-items:center;gap:8px;margin-bottom:8px;}
.fd-progress-label{font-size:11px;color:#1F2937;font-weight:500;width:90px;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.fd-progress-bar{flex:1;height:7px;background:#F3F4F6;border-radius:4px;overflow:hidden;}
.fd-progress-fill{height:100%;border-radius:4px;}
.fd-progress-val{font-size:11px;color:#6B7280;font-weight:600;width:55px;text-align:right;}

/* xcrud overlay */
.xcrud-row-header{background:linear-gradient(135deg,#2AABB3,#1E8F96)!important;}
.xcrud-row-header td,.xcrud-row-header th{color:#fff!important;font-family:'Poppins',sans-serif!important;font-size:12px!important;font-weight:600!important;}
.xcrud-list-container{border-radius:10px!important;overflow:hidden!important;border:1px solid #E5E7EB!important;}
.xcrud-list-container table{font-family:'Poppins',sans-serif!important;}
.xcrud-list-container td{font-size:12px!important;}
.xcrud-list-container tr:hover td{background:#E6F7F8!important;}
.xcrud-top-actions a,.xcrud-top-actions button{border-radius:6px!important;font-family:'Poppins',sans-serif!important;}
.xcrud-nav a{border-radius:4px!important;}
.xcrud-nav a:hover,.xcrud-nav a.active{background:#2AABB3!important;color:#fff!important;}
.xcrud-container{border:none!important;box-shadow:none!important;}

/* Responsive */
@media(max-width:1200px){.fd-kpi-grid{grid-template-columns:repeat(2,1fr);}}
@media(max-width:768px){.fd-kpi-grid{grid-template-columns:1fr;}.fd-chart-grid,.fd-panel-grid{grid-template-columns:1fr;}.fd-banner{padding:16px;}.fd-banner h1{font-size:16px;}}

/* Dashboard collapse */
.fd-dashboard{transition:max-height 0.4s ease,opacity 0.3s ease;overflow:hidden;}
.fd-dashboard.hidden{max-height:0!important;opacity:0;padding:0!important;margin:0!important;}
</style>

<div class="fd-page" style="padding:0 8px;">

<!-- ── Banner ── -->
<div class="fd-banner">
    <div>
        <h1><i class="fas fa-file-invoice-dollar" style="margin-right:7px;"></i> Fixed Deductions Management</h1>
        <div class="fd-breadcrumb">
            <a href="index.php"><i class="fas fa-home"></i> Home</a><span>/</span>
            <a href="#">Payroll</a><span>/</span><span>Fixed Deductions</span>
        </div>
    </div>
    <div>
        <button class="fd-banner-btn" onclick="window.location.reload()"><i class="fas fa-sync-alt"></i> Refresh</button>
        <button class="fd-banner-btn" onclick="fdExportCSV()"><i class="fas fa-download"></i> Export</button>
    </div>
</div>

<!-- ── Toggle ── -->
<div class="fd-dash-toggle" id="fd-dash-toggle" onclick="fdToggleDash()">
    <i class="fas fa-chevron-down"></i>
    <span>Dashboard Overview</span>
    <span style="font-size:11px;font-weight:400;color:#6B7280;margin-left:4px;" id="fd-toggle-hint">(click to collapse)</span>
</div>

<!-- ── Dashboard ── -->
<div class="fd-dashboard" id="fd-dashboard">

    <!-- KPI Row 1 -->
    <div class="fd-kpi-grid">
        <div class="fd-kpi-card">
            <div class="fd-kpi-icon primary"><i class="fas fa-layer-group"></i></div>
            <div><div class="fd-kpi-value"><?php echo number_format($totalDeductions); ?></div><div class="fd-kpi-label">Total Deductions</div></div>
        </div>
        <div class="fd-kpi-card warning">
            <div class="fd-kpi-icon warning"><i class="fas fa-clock"></i></div>
            <div><div class="fd-kpi-value"><?php echo number_format($pendingCount); ?></div><div class="fd-kpi-label">Pending</div></div>
        </div>
        <div class="fd-kpi-card success">
            <div class="fd-kpi-icon success"><i class="fas fa-check-circle"></i></div>
            <div><div class="fd-kpi-value"><?php echo number_format($completedCount); ?></div><div class="fd-kpi-label">Completed</div></div>
        </div>
        <div class="fd-kpi-card danger">
            <div class="fd-kpi-icon danger"><i class="fas fa-dollar-sign"></i></div>
            <div><div class="fd-kpi-value">$<?php echo number_format($totalAmountPending,2); ?></div><div class="fd-kpi-label">Pending Amount</div></div>
        </div>
    </div>

    <!-- KPI Row 2 -->
    <div class="fd-kpi-grid">
        <div class="fd-kpi-card info">
            <div class="fd-kpi-icon info"><i class="fas fa-money-check-alt"></i></div>
            <div><div class="fd-kpi-value">$<?php echo number_format($totalDeductionAmount,2); ?></div><div class="fd-kpi-label">Per-Cycle (Active)</div></div>
        </div>
        <div class="fd-kpi-card success">
            <div class="fd-kpi-icon success"><i class="fas fa-check-double"></i></div>
            <div><div class="fd-kpi-value">$<?php echo number_format($totalAmountCompleted,2); ?></div><div class="fd-kpi-label">Completed Total</div></div>
        </div>
        <div class="fd-kpi-card">
            <div class="fd-kpi-icon primary"><i class="fas fa-ban"></i></div>
            <div><div class="fd-kpi-value"><?php echo number_format($cancelledCount); ?></div><div class="fd-kpi-label">Cancelled</div></div>
        </div>
        <div class="fd-kpi-card warning">
            <div class="fd-kpi-icon warning"><i class="fas fa-exclamation-triangle"></i></div>
            <div><div class="fd-kpi-value"><?php echo count($highValueAlerts); ?></div><div class="fd-kpi-label">High-Value (&gt;$1K)</div></div>
        </div>
    </div>

    <!-- Charts Row 1 -->
    <div class="fd-chart-grid">
        <div class="fd-chart-card">
            <div class="fd-chart-title"><i class="fas fa-chart-bar"></i> By Category (Top 6)</div>
            <div class="fd-chart-wrap"><canvas id="fdCatChart"></canvas></div>
        </div>
        <div class="fd-chart-card">
            <div class="fd-chart-title"><i class="fas fa-chart-pie"></i> Status Distribution</div>
            <div class="fd-chart-wrap"><canvas id="fdStatusChart"></canvas></div>
        </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="fd-chart-grid">
        <div class="fd-chart-card">
            <div class="fd-chart-title"><i class="fas fa-building"></i> Pending by Department</div>
            <div class="fd-chart-wrap"><canvas id="fdDeptChart"></canvas></div>
        </div>
        <div class="fd-chart-card">
            <div class="fd-chart-title"><i class="fas fa-calendar-alt"></i> Pay Cycle Breakdown</div>
            <div class="fd-chart-wrap"><canvas id="fdCycleChart"></canvas></div>
        </div>
    </div>

    <!-- Panels -->
    <div class="fd-panel-grid">
        <div class="fd-panel-card">
            <div class="fd-panel-title"><i class="fas fa-history"></i> Recent Deductions</div>
            <div id="fd-recent"></div>
        </div>
        <div class="fd-panel-card">
            <div class="fd-panel-title"><i class="fas fa-users"></i> Top Employees (Pending)</div>
            <div id="fd-topemp"></div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if(count($highValueAlerts)>0): ?>
    <div style="margin-bottom:20px;">
        <div class="fd-panel-title" style="margin-bottom:8px;"><i class="fas fa-exclamation-triangle" style="color:#FAAD14;"></i> High-Value Alerts</div>
        <div id="fd-alerts"></div>
    </div>
    <?php endif; ?>

    <!-- Department Progress -->
    <?php if(count($byDepartment)>0): ?>
    <div class="fd-chart-card" style="margin-bottom:20px;">
        <div class="fd-chart-title"><i class="fas fa-chart-line"></i> Department Distribution</div>
        <div id="fd-deptprog"></div>
    </div>
    <?php endif; ?>

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

<!-- ══════════════════════════════════════
     xcrud Section (100% preserved)
     ══════════════════════════════════════ -->
<script src="angular/angular.min.js"></script>
<?php
echo '<div class="col-sm-12">';
include('xcrud/xcrud.php');
$userid = $_SESSION['UserID'];

if ($userid == 'admin' || $userid == 'ravinesh' || $userid == 'rajnal' || $userid == 'pchand' || $userid == 'jprasad'||$userid == 'ilimo' ||  $userid == 'mkhan' || $userid == 'waisake' ||$userid == 'salata'||$userid == 'lani' ||$userid == 'duta' || $userid == 'walesi' || $userid == 'pritika' || $userid == 'amelia' || $userid == 'clorissa' || $userid == 'ravneet'|| $userid == 'nitika'|| $userid == 'Priti' || $userid == 'sharukh' || $userid == 'mosheed'|| $userid == 'priyakumar') {
    $ebusiness = Xcrud::get_instance();
    $ebusiness->table('fixeddeductions');
    $ebusiness->show_primary_ai_column(true);
    $ebusiness->order_by('id','desc');
    $ebusiness->relation('employeeid','employeemaster','employeeid',array('employeeid','first_name','middle_name','last_name'));
    $ebusiness->relation('name','fixed_deduction_codecategory','id',array('name','code'));
    $ebusiness->relation('type','payrol_adjustments_type_details','id','type_detail',array('typeid' => '2'));
    $ebusiness->disabled('log');
    $ebusiness->change_type('pay_cycle','select','weekly','weekly,fortnightly,monthly');
    $ebusiness->change_type('status','select','pending','pending,completed,cancelled');
    $ebusiness->before_insert('fixed_deductions');
    $ebusiness->before_update('fixed_deductions');
    $ebusiness->set_attr('type',array('id'=>'type'));
    $ebusiness->set_attr('allow_upto_75_percent',array('id'=>'allow'));
    $ebusiness->relation('department','department','departmentid','departmentname');
    echo $ebusiness->render();
}
else{
    echo "Not Authorized to view this content";
}
echo '</div>';
?>

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

<div id="m_scroll_top" class="m-scroll-top"><i class="la la-arrow-up"></i></div>
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

<?php
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']; }
?>

<!-- ══════════════════════════════════════
     Dashboard JS — Optimized
     • animation:false on ALL charts
     • maintainAspectRatio:false + fixed 200px wrapper
     • maxBarThickness capped to prevent tall bars
     • data capped at 6 items per chart
     ══════════════════════════════════════ -->
<script>
document.addEventListener('DOMContentLoaded', function(){
    // Kill loader
    var lm = document.getElementById('fd-loading-modal');
    if(lm) lm.style.display = 'none';
    clearInterval(window._fdT);

    var CAT   = <?php echo $byCategoryJSON; ?>;
    var DEPT  = <?php echo $byDepartmentJSON; ?>;
    var CYCLE = <?php echo $byPayCycleJSON; ?>;
    var RECENT = <?php echo $recentJSON; ?>;
    var HV    = <?php echo $highValueJSON; ?>;
    var TOPEMP = <?php echo $topEmployeesJSON; ?>;

    var COLORS = ['#2AABB3','#1E8F96','#187278','#52C41A','#FAAD14','#FF4D4F'];

    /* Shared chart options: no animation, responsive, fill container */
    var BASE = {animation:false, responsive:true, maintainAspectRatio:false};

    /* ── Category Bar Chart ── */
    if(CAT.length > 0){
        new Chart(document.getElementById('fdCatChart'), {
            type: 'bar',
            data: {
                labels: CAT.map(function(d){ return d.name && d.name.length>14 ? d.name.substring(0,14)+'…' : d.name; }),
                datasets: [{
                    data: CAT.map(function(d){ return d.count; }),
                    backgroundColor: COLORS.slice(0, CAT.length),
                    borderRadius: 5,
                    barThickness: 22,
                    maxBarThickness: 28
                }]
            },
            options: Object.assign({}, BASE, {
                plugins: { legend: {display:false} },
                scales: {
                    y: { beginAtZero:true, ticks:{stepSize:1, font:{size:10}} },
                    x: { ticks:{font:{size:10}} }
                }
            })
        });
    }

    /* ── Status Doughnut ── */
    new Chart(document.getElementById('fdStatusChart'), {
        type: 'doughnut',
        data: {
            labels: ['Pending','Completed','Cancelled'],
            datasets: [{
                data: [<?php echo $pendingCount.','.$completedCount.','.$cancelledCount; ?>],
                backgroundColor: ['#FAAD14','#52C41A','#FF4D4F'],
                borderWidth: 2, borderColor: '#fff'
            }]
        },
        options: Object.assign({}, BASE, {
            cutout: '58%',
            plugins: { legend:{position:'bottom', labels:{padding:10, usePointStyle:true, font:{size:11}}} }
        })
    });

    /* ── Department Horizontal Bar ── */
    if(DEPT.length > 0){
        new Chart(document.getElementById('fdDeptChart'), {
            type: 'bar',
            data: {
                labels: DEPT.map(function(d){ return d.name && d.name.length>14 ? d.name.substring(0,14)+'…' : d.name; }),
                datasets: [{
                    data: DEPT.map(function(d){ return d.amount; }),
                    backgroundColor: '#2AABB3',
                    borderRadius: 5,
                    barThickness: 18,
                    maxBarThickness: 24
                }]
            },
            options: Object.assign({}, BASE, {
                indexAxis: 'y',
                plugins: { legend:{display:false} },
                scales: {
                    x: { beginAtZero:true, ticks:{callback:function(v){return '$'+v.toLocaleString();}, font:{size:10}} },
                    y: { ticks:{font:{size:10}} }
                }
            })
        });
    }

    /* ── Pay Cycle Doughnut ── */
    if(CYCLE.length > 0){
        new Chart(document.getElementById('fdCycleChart'), {
            type: 'doughnut',
            data: {
                labels: CYCLE.map(function(d){ return d.cycle+' ('+d.count+')'; }),
                datasets: [{
                    data: CYCLE.map(function(d){ return d.amount; }),
                    backgroundColor: ['#2AABB3','#FAAD14','#1890FF','#52C41A'],
                    borderWidth: 2, borderColor: '#fff'
                }]
            },
            options: Object.assign({}, BASE, {
                cutout: '55%',
                plugins: { legend:{position:'bottom', labels:{padding:10, usePointStyle:true, font:{size:11}}} }
            })
        });
    }

    /* ── Recent Deductions ── */
    var rEl = document.getElementById('fd-recent');
    if(rEl){
        if(RECENT.length > 0){
            var h = '';
            RECENT.forEach(function(d){
                var n = ((d.first_name||'')+' '+(d.last_name||'')).trim();
                var s = (d.status||'pending').toLowerCase();
                h += '<div class="fd-list-row">'
                    + '<div style="flex:1"><div class="fd-list-name">'+n+'</div>'
                    + '<div class="fd-list-sub">'+(d.category_name||'N/A')+' <span class="fd-status-badge '+s+'">'+s+'</span></div></div>'
                    + '<div class="fd-list-amount">$'+(parseFloat(d.deduction_amount)||0).toLocaleString(undefined,{minimumFractionDigits:2})
                    + '<div class="fd-list-sub" style="text-align:right">/cycle</div></div></div>';
            });
            rEl.innerHTML = h;
        } else {
            rEl.innerHTML = '<div style="color:#9CA3AF;font-size:12px;text-align:center;padding:16px">No data</div>';
        }
    }

    /* ── Top Employees ── */
    var tEl = document.getElementById('fd-topemp');
    if(tEl){
        if(TOPEMP.length > 0){
            var h2 = '';
            TOPEMP.forEach(function(d){
                var n = ((d.first_name||'')+' '+(d.last_name||'')).trim();
                h2 += '<div class="fd-list-row">'
                    + '<div style="flex:1"><div class="fd-list-name">'+n+'</div>'
                    + '<div class="fd-list-sub">'+d.ded_count+' ded · $'+(parseFloat(d.per_cycle)||0).toLocaleString(undefined,{minimumFractionDigits:2})+'/cycle</div></div>'
                    + '<div class="fd-list-amount">$'+(parseFloat(d.total_amt)||0).toLocaleString(undefined,{minimumFractionDigits:2})+'</div></div>';
            });
            tEl.innerHTML = h2;
        } else {
            tEl.innerHTML = '<div style="color:#9CA3AF;font-size:12px;text-align:center;padding:16px">No data</div>';
        }
    }

    /* ── Alerts ── */
    var aEl = document.getElementById('fd-alerts');
    if(aEl && HV.length > 0){
        var h3 = '';
        HV.forEach(function(d){
            var n = ((d.first_name||'')+' '+(d.last_name||'')).trim();
            var est = d.estimate_cycle ? (' · ~'+Math.round(d.estimate_cycle)+' cycles') : '';
            h3 += '<div class="fd-alert-row"><i class="fas fa-exclamation-triangle"></i>'
                + '<span><strong>'+n+'</strong> — '+(d.category_name||'N/A')+est+'</span>'
                + '<span class="fd-alert-amt">$'+(parseFloat(d.total_amount_to_deduct)||0).toLocaleString(undefined,{minimumFractionDigits:2})+'</span></div>';
        });
        aEl.innerHTML = h3;
    }

    /* ── Progress Bars ── */
    var pEl = document.getElementById('fd-deptprog');
    if(pEl && DEPT.length > 0){
        var mx = Math.max.apply(null, DEPT.map(function(d){return d.amount;}));
        var h4 = '';
        DEPT.forEach(function(d, i){
            var pct = mx > 0 ? Math.round((d.amount/mx)*100) : 0;
            h4 += '<div class="fd-progress-wrap">'
                + '<div class="fd-progress-label" title="'+d.name+'">'+d.name+'</div>'
                + '<div class="fd-progress-bar"><div class="fd-progress-fill" style="width:'+pct+'%;background:'+COLORS[i%COLORS.length]+'"></div></div>'
                + '<div class="fd-progress-val">$'+d.amount.toLocaleString()+'</div></div>';
        });
        pEl.innerHTML = h4;
    }
});

/* ── Dashboard Toggle + localStorage ── */
function fdToggleDash(){
    var d=document.getElementById('fd-dashboard'), t=document.getElementById('fd-dash-toggle'), h=document.getElementById('fd-toggle-hint');
    if(d.classList.contains('hidden')){
        d.classList.remove('hidden'); d.style.maxHeight=d.scrollHeight+'px';
        t.classList.remove('collapsed'); h.textContent='(click to collapse)';
        localStorage.setItem('fd_dash','0');
    } else {
        d.classList.add('hidden'); t.classList.add('collapsed');
        h.textContent='(click to expand)'; localStorage.setItem('fd_dash','1');
    }
}
(function(){
    if(localStorage.getItem('fd_dash')==='1'){
        var d=document.getElementById('fd-dashboard'), t=document.getElementById('fd-dash-toggle'), h=document.getElementById('fd-toggle-hint');
        if(d){d.classList.add('hidden'); t.classList.add('collapsed'); h.textContent='(click to expand)';}
    }
})();

/* ── CSV Export ── */
function fdExportCSV(){
    var R=<?php echo $recentJSON; ?>;
    if(!R||!R.length){alert('No data');return;}
    var csv='Employee,Category,Deduction,Total,Status,Cycle,Est\n';
    R.forEach(function(d){
        csv+='"'+((d.first_name||'')+' '+(d.last_name||''))+'","'+(d.category_name||'')+'",'
            +(d.deduction_amount||0)+','+(d.total_amount_to_deduct||0)+','
            +(d.status||'')+','+(d.pay_cycle||'')+','+(d.estimate_cycle||'')+'\n';
    });
    var b=new Blob([csv],{type:'text/csv'}), u=URL.createObjectURL(b), a=document.createElement('a');
    a.href=u; a.download='fixed_deductions_'+new Date().toISOString().slice(0,10)+'.csv'; a.click();
    URL.revokeObjectURL(u);
}
</script>

<!-- xcrud type/allow handler (preserved) -->
<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest", function(){
    $(".xcrud").on("change", "#type", function(){
        if($(this).val() == "12"){ $("#allow").prop("disabled", false); }
        else { $("#allow").prop("disabled", true); }
    });
});
</script>
