<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<?php $isSalesUser = has_role('sales_user'); ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<div class="container-fluid p-4 page-dashboard">
  <?php if ($isSalesUser): ?>
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="mb-0"><i class="bi bi-speedometer2 me-2"></i>Sales Dashboard</h4>
      <div class="text-muted small">Branch: <?php echo htmlspecialchars($_SESSION['branch_name'] ?? 'Not Selected'); ?></div>
    </div>
  </div>
  <?php endif; ?>
  <?php if (has_role(['admin','super_admin'])): ?>
  <div class="d-flex justify-content-end align-items-center mb-3 gap-2">
    <label class="small text-muted mb-0">Branch</label>
    <select id="dash_branch" class="form-select form-select-sm" style="max-width:260px"></select>
    <button class="btn btn-sm btn-primary" id="btnOrderForm"><i class="bi bi-upload me-1"></i> Order Form</button>
  </div>
  <?php endif; ?>
  <div class="row g-3">
    <div class="col-12">
      <div class="row g-3">
        <div class="col-sm-6 col-lg-3">
          <div class="card shadow-sm border-0 h-100" style="background:linear-gradient(135deg,#6a11cb,#2575fc); color:#fff;">
            <div class="card-body p-3">
              <div class="d-flex justify-content-between align-items-center"><div class="fw-semibold">Revenue Today</div><i class="bi bi-cash-coin fs-4 opacity-75"></i></div>
              <div class="display-6" id="kpi_rev_today">LKR 0.00</div>
            </div>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="card shadow-sm border-0 h-100" style="background:linear-gradient(135deg,#11998e,#38ef7d); color:#fff;">
            <div class="card-body p-3">
              <div class="d-flex justify-content-between align-items-center mb-2"><div class="fw-semibold">Revenue Month</div><i class="bi bi-graph-up-arrow fs-4 opacity-75"></i></div>
              <ul class="nav nav-pills nav-fill mb-2" id="revMonthTabs" role="tablist" style="font-size:0.75rem;">
                <li class="nav-item" role="presentation">
                  <button class="nav-link active py-1 px-2" id="tab-sales" data-bs-toggle="tab" data-bs-target="#pane-sales" type="button" role="tab" style="background:rgba(255,255,255,0.2); color:#fff; border:none;">Total Sales</button>
                </li>
                <li class="nav-item" role="presentation">
                  <button class="nav-link py-1 px-2" id="tab-paid" data-bs-toggle="tab" data-bs-target="#pane-paid" type="button" role="tab" style="background:transparent; color:#fff; border:none;">Paid</button>
                </li>
              </ul>
              <div class="tab-content">
                <div class="tab-pane fade show active" id="pane-sales" role="tabpanel">
                  <div class="display-6" id="kpi_sales_month">LKR 0.00</div>
                </div>
                <div class="tab-pane fade" id="pane-paid" role="tabpanel">
                  <div class="display-6" id="kpi_paid_month">LKR 0.00</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="card shadow-sm border-0 h-100" style="background:linear-gradient(135deg,#f7971e,#ffd200); color:#000;">
            <div class="card-body p-3">
              <div class="d-flex justify-content-between align-items-center"><div class="fw-semibold">Outstanding</div><i class="bi bi-exclamation-triangle fs-4 opacity-75"></i></div>
              <div class="display-6" id="kpi_outstanding">LKR 0.00</div>
            </div>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="card shadow-sm border-0 h-100" style="background:linear-gradient(135deg,#ee0979,#ff6a00); color:#fff;">
            <div class="card-body p-3">
              <div class="d-flex justify-content-between align-items-center"><div class="fw-semibold">Customers</div><i class="bi bi-people fs-4 opacity-75"></i></div>
              <div class="display-6" id="kpi_customers">0</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-12 col-lg-8">
      <div class="card shadow-sm h-100">
        <div class="card-header bg-white"><strong>Sales Trend (Last 6 Months)</strong></div>
        <div class="card-body"><canvas id="chTrend" height="120"></canvas></div>
      </div>
    </div>
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm h-100">
        <div class="card-header bg-white"><strong>Available Colors (%)</strong></div>
        <div class="card-body"><canvas id="chFinishes" height="120"></canvas></div>
      </div>
    </div>

    <?php if (!$isSalesUser): ?>
    <div class="col-12">
      <div class="card shadow-sm">
        <div class="card-header bg-white">
          <ul class="nav nav-tabs card-header-tabs" id="dashTabs" role="tablist">
            <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-age" type="button">Outstanding Age</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-alerts" type="button">Alerts</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-exp" type="button">Expenditures</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-pay" type="button">Salary</button></li>
          </ul>
        </div>
        <div class="card-body tab-content">
          <div class="tab-pane fade show active" id="tab-age">
            <div class="row text-center">
              <div class="col-6 col-md-3"><div class="p-3 rounded-3 bg-light"><div class="small text-muted">0-7 Days</div><div class="fs-4" id="age_0_7">LKR 0.00</div></div></div>
              <div class="col-6 col-md-3"><div class="p-3 rounded-3 bg-light"><div class="small text-muted">8-30 Days</div><div class="fs-4" id="age_8_30">LKR 0.00</div></div></div>
              <div class="col-6 col-md-3 mt-3 mt-md-0"><div class="p-3 rounded-3 bg-light"><div class="small text-muted">31-60 Days</div><div class="fs-4" id="age_31_60">LKR 0.00</div></div></div>
              <div class="col-6 col-md-3 mt-3 mt-md-0"><div class="p-3 rounded-3 bg-light"><div class="small text-muted">60+ Days</div><div class="fs-4" id="age_60p">LKR 0.00</div></div></div>
            </div>
          </div>
          <div class="tab-pane fade" id="tab-alerts">
            <div id="dashAlerts" class="text-muted">Loading...</div>
          </div>
          <div class="tab-pane fade" id="tab-exp">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <strong>Recent Expenditures</strong>
              <a class="btn btn-sm btn-outline-secondary" href="<?php echo url_for('index.php?page=expenditures'); ?>">View All</a>
            </div>
            <div class="table-responsive">
              <table class="table table-sm" id="tblExp"><thead><tr><th>Date</th><th>Description</th><th>Category</th><th class="text-end">Amount (LKR)</th></tr></thead><tbody></tbody><tfoot><tr><th colspan="3">This Month</th><th class="text-end" id="expMonth">LKR 0.00</th></tr></tfoot></table>
            </div>
          </div>
          <div class="tab-pane fade" id="tab-pay">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <strong>Recent Payroll</strong>
              <a class="btn btn-sm btn-outline-secondary" href="<?php echo url_for('index.php?page=salary_management'); ?>">Manage Salary</a>
            </div>
            <div class="table-responsive">
              <table class="table table-sm" id="tblPay"><thead><tr><th>Employee</th><th>Period</th><th>Status</th><th class="text-end">Net (LKR)</th></tr></thead><tbody></tbody></table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

  </div>
</div>

<div class="container-fluid px-4 pb-4">
  <div class="row g-3">
    <div class="col-12">
      <h5 class="mb-2">Raw Materials Inventory</h5>
      <div class="row g-2" id="rawTiles">
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=import_raw_materials'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#3b82f6"><div class="d-flex justify-content-between"><div class="small opacity-75">Total Materials</div><i class="bi bi-box"></i></div><div class="fs-4" id="raw_total">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=import_raw_materials'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#10b981"><div class="d-flex justify-content-between"><div class="small opacity-75">Available</div><i class="bi bi-check2-circle"></i></div><div class="fs-4" id="raw_received">0</div><div class="small opacity-75" id="raw_received_sqft">SQF 0.000</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=polishing'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#f59e0b"><div class="d-flex justify-content-between"><div class="small opacity-75">In Polishing</div><i class="bi bi-scissors"></i></div><div class="fs-4" id="raw_in_polishing">0</div><div class="small opacity-75" id="raw_in_polishing_sqft">SQF 0.000</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=finished_products'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#0ea5e9"><div class="d-flex justify-content-between"><div class="small opacity-75">Finished</div><i class="bi bi-flag"></i></div><div class="fs-4" id="raw_finished">0</div><div class="small opacity-75" id="raw_finished_sqft">SQF 0.000</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=import_raw_materials'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#7c3aed"><div class="d-flex justify-content-between"><div class="small opacity-75">Total Value</div><i class="bi bi-currency-exchange"></i></div><div class="fs-4" id="raw_value">LKR 0.00</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=import_raw_materials'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#374151"><div class="d-flex justify-content-between"><div class="small opacity-75">Total Sq.Ft</div><i class="bi bi-bounding-box"></i></div><div class="fs-4" id="raw_sqft">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=import_raw_materials'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 text-white" style="background:#1f2937"><div class="d-flex justify-content-between"><div class="small opacity-75">Total Sq.M</div><i class="bi bi-grid-3x3-gap"></i></div><div class="fs-4" id="raw_sqm">0</div></div></a></div>
      </div>
    </div>

    <div class="col-12">
      <h5 class="mt-4 mb-2">Finished Products</h5>
      <div class="row g-2">
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=finished_products'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Total</div><i class="bi bi-box-seam"></i></div><div class="fs-4 text-dark" id="fin_total">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=finished_products'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Available</div><i class="bi bi-check2-circle"></i></div><div class="fs-4 text-dark" id="fin_avail">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=finished_products'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Reserved</div><i class="bi bi-hourglass-split"></i></div><div class="fs-4 text-dark" id="fin_resv">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=finished_products'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Sold</div><i class="bi bi-bag-check"></i></div><div class="fs-4 text-dark" id="fin_sold">0</div></div></a></div>
      </div>
    </div>

    <div class="col-12">
      <h5 class="mt-4 mb-2">Cutting Inventory</h5>
      <div class="row g-2">
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=cutting_inventory'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Total Pieces</div><i class="bi bi-stack"></i></div><div class="fs-4 text-dark" id="cut_total">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=cutting_inventory'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Available</div><i class="bi bi-check2-circle"></i></div><div class="fs-4 text-dark" id="cut_avail">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=cutting_inventory'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Usable</div><i class="bi bi-tools"></i></div><div class="fs-4 text-dark" id="cut_usable">0</div></div></a></div>
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=cutting_inventory'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Total Sq.Ft</div><i class="bi bi-bounding-box"></i></div><div class="fs-4 text-dark" id="cut_sqft">0</div></div></a></div>
      </div>
    </div>

    <div class="col-12">
      <h5 class="mt-4 mb-2">Production Inventory</h5>
      <div class="row g-2">
        <div class="col-6 col-md-3"><a href="<?php echo url_for('index.php?page=production'); ?>" class="text-decoration-none"><div class="p-3 rounded-3 bg-light"><div class="d-flex justify-content-between"><div class="small text-muted">Total Items</div><i class="bi bi-hammer"></i></div><div class="fs-4 text-dark" id="prod_total">0</div></div></a></div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="orderFormModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Order Form Match</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="orderFormUpload" enctype="multipart/form-data">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <div class="row g-3 align-items-end">
            <div class="col-md-6">
              <label class="form-label">CSV File</label>
              <input type="file" class="form-control" name="csv" id="orderFormFile" accept=".csv" required>
              <div class="form-text">Units: inches. Required columns: Width and Height (header names can be width/height or w/h).</div>
            </div>
            <div class="col-md-6 d-flex gap-2">
              <button type="submit" class="btn btn-primary" id="btnOrderFormRun"><i class="bi bi-play"></i> Match</button>
              <button type="button" class="btn btn-outline-secondary" id="btnOrderFormClear">Clear</button>
            </div>
          </div>

          <div class="mt-3" id="orderFormSummary" style="display:none;">
            <div class="row g-2">
              <div class="col-md-3"><div class="border rounded p-2"><div class="text-muted small">Rows</div><div class="fs-5" id="of_rows">0</div></div></div>
              <div class="col-md-3"><div class="border rounded p-2"><div class="text-muted small">Raw Matches</div><div class="fs-5" id="of_raw">0</div></div></div>
              <div class="col-md-3"><div class="border rounded p-2"><div class="text-muted small">Finished Matches</div><div class="fs-5" id="of_fin">0</div></div></div>
              <div class="col-md-3"><div class="border rounded p-2"><div class="text-muted small">Cut Matches</div><div class="fs-5" id="of_cut">0</div></div></div>
            </div>
          </div>

          <div class="table-responsive mt-3 border rounded" id="orderFormResultsWrap" style="display:none;">
            <table class="table table-sm align-middle mb-0" id="orderFormResults">
              <thead class="table-light">
                <tr>
                  <th style="width:80px;">Row</th>
                  <th style="width:160px;">Width (in)</th>
                  <th style="width:160px;">Height (in)</th>
                  <th>Raw (slabs)</th>
                  <th>Finished</th>
                  <th>Cut Pieces</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function(){
  if (!$('.page-dashboard').length) return;
  const fmt = n => Number(n||0).toLocaleString('en-LK',{style:'currency',currency:'LKR'});
  function p(obj){
    const $b=$('#dash_branch'); if($b.length){ const v=$b.val(); if(v) obj.branch_id=v; }
    return obj;
  }
  function loadBranches(){
    const $b=$('#dash_branch'); if(!$b.length) return;
    const sessBid = <?php echo json_encode((int)($_SESSION['branch_id'] ?? 0)); ?>;
    $.get('api/branches.php',{ action:'list' }, function(res){
      $b.empty(); $b.append('<option value="">All Branches</option>');
      (res.data||[]).forEach(br=> $b.append(`<option value="${br.id}">${$('<div>').text(br.name).html()}</option>`));
      if (sessBid && $b.find(`option[value="${sessBid}"]`).length){ $b.val(String(sessBid)); }
      $b.trigger('change');
    });
  }

  // KPIs
  $.get('api/dashboard.php', p({ action:'kpis' }), function(res){
    const d=res.data||{};
    $('#kpi_rev_today').text(fmt(d.revenue_today||0));
    $('#kpi_sales_month').text(fmt(d.sales_month||0));
    $('#kpi_paid_month').text(fmt(d.paid_month||0));
    $('#kpi_outstanding').text(fmt(d.outstanding||0));
    $('#kpi_customers').text((d.customers||0).toLocaleString());
  });

  // Inventory tiles
  $.get('api/dashboard.php', p({ action:'raw_inventory' }), function(res){ const d=res.data||{}; $('#raw_total').text(d.total||0); $('#raw_received').text(d.received||0); $('#raw_in_polishing').text(d.in_polishing||0); $('#raw_finished').text(d.finished||0); $('#raw_value').text(fmt(d.value||0)); $('#raw_sqft').text((d.sq_ft||0).toFixed(3)); $('#raw_sqm').text((d.sq_m2||0).toFixed(3)); $('#raw_received_sqft').text('SQF ' + (d.received_sq_ft||0).toFixed(3)); $('#raw_in_polishing_sqft').text('SQF ' + (d.in_polishing_sq_ft||0).toFixed(3)); $('#raw_finished_sqft').text('SQF ' + (d.finished_sq_ft||0).toFixed(3)); });
  $.get('api/dashboard.php', p({ action:'final_inventory' }), function(res){ const d=res.data||{}; $('#fin_total').text(d.total||0); $('#fin_avail').text(d.available||0); $('#fin_resv').text(d.reserved||0); $('#fin_sold').text(d.sold||0); });
  $.get('api/dashboard.php', p({ action:'cut_inventory' }), function(res){ const d=res.data||{}; $('#cut_total').text(d.total||0); $('#cut_avail').text(d.available||0); $('#cut_usable').text(d.usable||0); $('#cut_sqft').text((d.area_sq_ft||0).toFixed(3)); });
  $.get('api/dashboard.php', p({ action:'production_inventory' }), function(res){ const d=res.data||{}; $('#prod_total').text(d.total||0); });

  // Expenditures table
  $.get('api/dashboard.php', p({ action:'recent_expenditures' }), function(res){ const rows=res.data||[]; const $tb=$('#tblExp tbody'); $tb.empty(); if(!rows.length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No records</td></tr>'); } else { rows.forEach(r=> $tb.append(`<tr><td>${r.exp_date||''}</td><td>${$('<div>').text(r.description||'').html()}</td><td>${$('<div>').text(r.category||'').html()}</td><td class=\"text-end\">${Number(r.amount||0).toFixed(2)}</td></tr>`)); } $('#expMonth').text((Number(res.month_total||0)).toLocaleString('en-LK',{style:'currency',currency:'LKR'})); });

  // Payroll table
  $.get('api/dashboard.php', { action:'recent_payroll' }, function(res){ const rows=res.data||[]; const $tb=$('#tblPay tbody'); $tb.empty(); if(!rows.length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No records</td></tr>'); } else { rows.forEach(r=> $tb.append(`<tr><td>${$('<div>').text(r.employee_name||'').html()}</td><td>${String(r.period_year||'')}-${String(r.period_month||'').padStart(2,'0')}</td><td>${r.paid_on? 'Paid':'Unpaid'}</td><td class=\"text-end\">${Number(r.net_salary||0).toFixed(2)}</td></tr>`)); } });

  // Sales Trend
  $.get('api/dashboard.php', p({ action:'sales_trend' }), function(res){
    const rows=res.data||[];
    const labels=rows.map(r=>r.ym);
    const sales=rows.map(r=>Number(r.sales_value||0));
    const paid=rows.map(r=>Number(r.paid_value||0));
    new Chart(document.getElementById('chTrend'), {
      type:'line',
      data:{
        labels,
        datasets:[
          { label:'Sales Value', data:sales, fill:false, borderColor:'#2575fc', tension:.2 },
          { label:'Paid Value', data:paid, fill:false, borderColor:'#28a745', tension:.2 }
        ]
      },
      options:{
        plugins:{
          legend:{ display:true, position:'bottom' },
          tooltip:{
            callbacks:{
              label: (ctx) => {
                const v = Number(ctx.parsed.y || 0);
                return `${ctx.dataset.label}: ${v.toLocaleString('en-LK',{style:'currency',currency:'LKR'})}`;
              }
            }
          }
        },
        scales:{ y:{ ticks:{ callback:v=>Number(v).toLocaleString('en-LK',{style:'currency',currency:'LKR'}) }}}
      }
    });
  });

  // Available Colors (%)
  $.get('api/dashboard.php', p({ action:'top_finishes' }), function(res){
    const rows=res.data||[];
    const labels=rows.map(r=>r.name||'Unknown');
    const abs=rows.map(r=>Number(r.total||0));
    const sum = abs.reduce((a,b)=>a+b,0) || 0;
    const pct = abs.map(v=> sum>0 ? (v*100/sum) : 0);
    const palette=['#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f','#edc949','#af7aa1','#ff9da7','#9c755f','#bab0ab'];
    new Chart(document.getElementById('chFinishes'), {
      type:'doughnut',
      data:{
        labels,
        datasets:[{ data:pct, backgroundColor:labels.map((_,i)=>palette[i%palette.length]) }]
      },
      options:{
        plugins:{
          legend:{ position:'bottom' },
          tooltip:{
            callbacks:{
              label: (ctx) => {
                const i = ctx.dataIndex;
                const p = Number(ctx.parsed||0);
                const v = Number(abs[i]||0);
                return `${ctx.label}: ${p.toFixed(1)}% (SQFT ${v.toFixed(3)})`;
              }
            }
          }
        }
      }
    });
  });

  // Outstanding Age
  $.get('api/dashboard.php', p({ action:'outstanding_age' }), function(res){
    const d=res.data||{}; $('#age_0_7').text(fmt(d.d0_7||0)); $('#age_8_30').text(fmt(d.d8_30||0)); $('#age_31_60').text(fmt(d.d31_60||0)); $('#age_60p').text(fmt(d.d60p||0));
  });

  // Alerts panel uses same endpoints as header
  $.when(
    $.get('api/reports.php', { action:'outstanding', next_week:1, from:'1970-01-01', to:'2999-12-31' }),
    $.get('api/reports.php', { action:'outstanding', overdue_invoice_days:7, from:'1970-01-01', to:'2999-12-31' })
  ).done(function(a,b){
    const nextRows=(a[0]&&a[0].data)||[]; const overRows=(b[0]&&b[0].data)||[];
    if(!nextRows.length && !overRows.length){ $('#dashAlerts').text('No upcoming or overdue invoices.'); return; }
    const $c=$('#dashAlerts').empty();
    if(nextRows.length){ $c.append(`<div class="mb-2"><i class="bi bi-clock-history me-1 text-warning"></i> ${nextRows.length} invoice(s) due in next 7 days.</div>`); }
    if(overRows.length){ $c.append(`<div><i class="bi bi-exclamation-octagon me-1 text-danger"></i> ${overRows.length} invoice(s) older than 7 days and unpaid.</div>`); }
  });
  loadBranches();
  function resetChartCanvas(id){ const $c = $('#'+id); const $p=$c.parent(); $c.remove(); $p.append(`<canvas id="${id}" height="120"></canvas>`); }
  $('#dash_branch').on('change', function(){
    // Reload all widgets bound to branch
    $.get('api/dashboard.php', p({ action:'kpis' }), function(res){ const d=res.data||{}; $('#kpi_rev_today').text(fmt(d.revenue_today||0)); $('#kpi_sales_month').text(fmt(d.sales_month||0)); $('#kpi_paid_month').text(fmt(d.paid_month||0)); $('#kpi_outstanding').text(fmt(d.outstanding||0)); $('#kpi_customers').text((d.customers||0).toLocaleString()); });
    $.get('api/dashboard.php', p({ action:'raw_inventory' }), function(res){ const d=res.data||{}; $('#raw_total').text(d.total||0); $('#raw_received').text(d.received||0); $('#raw_in_polishing').text(d.in_polishing||0); $('#raw_finished').text(d.finished||0); $('#raw_value').text(fmt(d.value||0)); $('#raw_sqft').text((d.sq_ft||0).toFixed(3)); $('#raw_sqm').text((d.sq_m2||0).toFixed(3)); $('#raw_received_sqft').text('SQF ' + (d.received_sq_ft||0).toFixed(3)); $('#raw_in_polishing_sqft').text('SQF ' + (d.in_polishing_sq_ft||0).toFixed(3)); $('#raw_finished_sqft').text('SQF ' + (d.finished_sq_ft||0).toFixed(3)); });
    $.get('api/dashboard.php', p({ action:'final_inventory' }), function(res){ const d=res.data||{}; $('#fin_total').text(d.total||0); $('#fin_avail').text(d.available||0); $('#fin_resv').text(d.reserved||0); $('#fin_sold').text(d.sold||0); });
    $.get('api/dashboard.php', p({ action:'cut_inventory' }), function(res){ const d=res.data||{}; $('#cut_total').text(d.total||0); $('#cut_avail').text(d.available||0); $('#cut_usable').text(d.usable||0); $('#cut_sqft').text((d.area_sq_ft||0).toFixed(3)); });
    $.get('api/dashboard.php', p({ action:'production_inventory' }), function(res){ const d=res.data||{}; $('#prod_total').text(d.total||0); });
    resetChartCanvas('chTrend');
    $.get('api/dashboard.php', p({ action:'sales_trend' }), function(res){
      const rows=res.data||[];
      const labels=rows.map(r=>r.ym);
      const sales=rows.map(r=>Number(r.sales_value||0));
      const paid=rows.map(r=>Number(r.paid_value||0));
      new Chart(document.getElementById('chTrend'), {
        type:'line',
        data:{
          labels,
          datasets:[
            { label:'Sales Value', data:sales, fill:false, borderColor:'#2575fc', tension:.2 },
            { label:'Paid Value', data:paid, fill:false, borderColor:'#28a745', tension:.2 }
          ]
        },
        options:{
          plugins:{
            legend:{ display:true, position:'bottom' },
            tooltip:{
              callbacks:{
                label: (ctx) => {
                  const v = Number(ctx.parsed.y || 0);
                  return `${ctx.dataset.label}: ${v.toLocaleString('en-LK',{style:'currency',currency:'LKR'})}`;
                }
              }
            }
          },
          scales:{ y:{ ticks:{ callback:v=>Number(v).toLocaleString('en-LK',{style:'currency',currency:'LKR'}) }}}
        }
      });
    });
    resetChartCanvas('chFinishes');
    $.get('api/dashboard.php', p({ action:'top_finishes' }), function(res){
      const rows=res.data||[];
      const labels=rows.map(r=>r.name||'Unknown');
      const abs=rows.map(r=>Number(r.total||0));
      const sum = abs.reduce((a,b)=>a+b,0) || 0;
      const pct = abs.map(v=> sum>0 ? (v*100/sum) : 0);
      const palette=['#4e79a7','#f28e2b','#e15759','#76b7b2','#59a14f','#edc949','#af7aa1','#ff9da7','#9c755f','#bab0ab'];
      new Chart(document.getElementById('chFinishes'), {
        type:'doughnut',
        data:{
          labels,
          datasets:[{ data:pct, backgroundColor:labels.map((_,i)=>palette[i%palette.length]) }]
        },
        options:{
          plugins:{
            legend:{ position:'bottom' },
            tooltip:{
              callbacks:{
                label: (ctx) => {
                  const i = ctx.dataIndex;
                  const p = Number(ctx.parsed||0);
                  const v = Number(abs[i]||0);
                  return `${ctx.label}: ${p.toFixed(1)}% (SQFT ${v.toFixed(3)})`;
                }
              }
            }
          }
        }
      });
    });
    $.get('api/dashboard.php', p({ action:'outstanding_age' }), function(res){ const d=res.data||{}; $('#age_0_7').text(fmt(d.d0_7||0)); $('#age_8_30').text(fmt(d.d8_30||0)); $('#age_31_60').text(fmt(d.d31_60||0)); $('#age_60p').text(fmt(d.d60p||0)); });
  });

  function resetOrderFormUI(){
    $('#orderFormUpload')[0].reset();
    $('#orderFormSummary').hide();
    $('#orderFormResultsWrap').hide();
    $('#orderFormResults tbody').empty();
    $('#of_rows').text('0');
    $('#of_raw').text('0');
    $('#of_fin').text('0');
    $('#of_cut').text('0');
  }

  $('#btnOrderForm').on('click', function(){
    resetOrderFormUI();
    $('#orderFormModal').modal('show');
  });

  $('#btnOrderFormClear').on('click', function(){
    resetOrderFormUI();
  });

  $('#orderFormUpload').on('submit', function(e){
    e.preventDefault();
    const fd = new FormData(this);
    const $btn = $('#btnOrderFormRun');
    if ($btn.data('busy')) return;
    $btn.data('busy', true);
    $btn.prop('disabled', true).text('Matching...');
    $.ajax({ url:'api/order_form_match.php', method:'POST', data: fd, contentType:false, processData:false })
      .done(function(res){
        const rows = res.rows || [];
        $('#orderFormSummary').show();
        $('#orderFormResultsWrap').show();
        $('#of_rows').text(String(res.summary?.rows ?? rows.length ?? 0));
        $('#of_raw').text(String(res.summary?.raw_matches ?? 0));
        $('#of_fin').text(String(res.summary?.final_matches ?? 0));
        $('#of_cut').text(String(res.summary?.cut_matches ?? 0));
        const $tb = $('#orderFormResults tbody').empty();
        if (!rows.length){
          $tb.append('<tr><td colspan="6" class="text-center text-muted">No rows found in file</td></tr>');
          return;
        }
        rows.forEach(r=>{
          const raw = r.raw_matches || [];
          const fin = r.final_matches || [];
          const cut = r.cut_matches || [];
          function fmtItem(x){
            const slab = (x && (x.slab_no || x.id)) ? String(x.slab_no || x.id) : '';
            const po = (x && (x.po_no || x.order_no)) ? String(x.po_no || x.order_no) : '';
            const label = slab ? slab : '-';
            const suffix = po ? ` (PO: ${po})` : '';
            return $('<div>').text(label + suffix).html();
          }
          const rawText = raw.length ? raw.slice(0,10).map(fmtItem).join(', ') + (raw.length>10?' ...':'') : '-';
          const finText = fin.length ? fin.slice(0,10).map(fmtItem).join(', ') + (fin.length>10?' ...':'') : '-';
          const cutText = cut.length ? cut.slice(0,10).map(fmtItem).join(', ') + (cut.length>10?' ...':'') : '-';
          const tr = $('<tr>');
          tr.append(`<td>${r.row_no ?? ''}</td>`);
          tr.append(`<td>${r.width_in ?? ''}</td>`);
          tr.append(`<td>${r.height_in ?? ''}</td>`);
          tr.append(`<td>${rawText}</td>`);
          tr.append(`<td>${finText}</td>`);
          tr.append(`<td>${cutText}</td>`);
          $tb.append(tr);
        });
      })
      .fail(function(xhr){
        alert((xhr.responseJSON && xhr.responseJSON.message) || 'Order form match failed');
      })
      .always(function(){
        $btn.data('busy', false);
        $btn.prop('disabled', false).html('<i class="bi bi-play"></i> Match');
      });
  });
})();
</script>
