<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
startSession(); requireLogin();
$db   = Database::getInstance();
$page = 'Dashboard';
$user = currentUser();

// Vendor has its own dashboard concept (Organizations & Licenses) — this
// whole analytics dashboard is company/employee data, not relevant to them.
if ($user['role'] === 'vendor') {
    header('Location: ' . BASE_URL . '/modules/companies/index.php'); exit;
}

// FIX (16 Jul 2026): every query below is scoped to the current
// organization (orgScopeClause() / organizationId()) — same pattern used
// everywhere else since the multi-org work. A dashboard with unscoped
// company-wide numbers would be exactly the kind of leak that's been
// fixed everywhere else.
[$empOrgClause, $empOrgParams]     = orgScopeClause($db, 'company_id');
[$empOrgClauseE, $empOrgParamsE]   = orgScopeClause($db, 'e.company_id');

// ── Financial year (India: 1 Apr – 31 Mar) ─────────────────────
$today = new DateTime();
if ((int)$today->format('n') >= 4) {
    $fyStartYear = (int)$today->format('Y');
} else {
    $fyStartYear = (int)$today->format('Y') - 1;
}
$financialYear = $fyStartYear . '-' . substr((string)($fyStartYear + 1), 2);
$fyStart = "$fyStartYear-04-01";
$fyEnd   = ($fyStartYear + 1) . '-03-31';

// ── 8 stat cards ────────────────────────────────────────────────
$activeEmployees = (int)$db->fetchValue("SELECT COUNT(*) FROM employees WHERE status='active' AND $empOrgClause", $empOrgParams);
$inactiveEmployees = (int)$db->fetchValue("SELECT COUNT(*) FROM employees WHERE status IN ('inactive','suspended','on_leave') AND $empOrgClause", $empOrgParams);

$joinedLast12 = (int)$db->fetchValue(
    "SELECT COUNT(*) FROM employees WHERE date_of_joining >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND $empOrgClause",
    $empOrgParams
);
$separatedLast12 = (int)$db->fetchValue(
    "SELECT COUNT(*) FROM separations s JOIN employees e ON e.id=s.employee_id
      WHERE s.last_working_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND $empOrgClauseE",
    $empOrgParamsE
);
$presentToday = (int)$db->fetchValue(
    "SELECT COUNT(*) FROM muster m JOIN employees e ON e.id=m.employee_id
      WHERE m.muster_date=CURDATE() AND m.status='P' AND $empOrgClauseE",
    $empOrgParamsE
);
$onLeaveToday = (int)$db->fetchValue(
    "SELECT COUNT(*) FROM muster m JOIN employees e ON e.id=m.employee_id
      WHERE m.muster_date=CURDATE() AND m.status='L' AND $empOrgClauseE",
    $empOrgParamsE
);

[$runOrgClause, $runOrgParams] = orgScopeClause($db, 'company_id');
$lastPayrollRun = $db->fetchOne(
    "SELECT * FROM payroll_runs WHERE $runOrgClause ORDER BY year DESC, month DESC LIMIT 1",
    $runOrgParams
);

$stats = [
    ['icon'=>'ti-user-check',   'cls'=>'green',  'val'=>number_format($activeEmployees),   'label'=>'Active Employees',              'link'=>'modules/reports/stat_detail.php?type=active'],
    ['icon'=>'ti-user-x',       'cls'=>'red',    'val'=>number_format($inactiveEmployees), 'label'=>'Inactive Employees',            'link'=>'modules/reports/stat_detail.php?type=inactive'],
    ['icon'=>'ti-calendar-stats','cls'=>'brand', 'val'=>$financialYear,                    'label'=>'Financial Year',                'link'=>'modules/reports/summary.php'],
    ['icon'=>'ti-receipt',      'cls'=>'blue',   'val'=>$lastPayrollRun ? monthName((int)$lastPayrollRun['month']).' '.$lastPayrollRun['year'] : '—', 'label'=>'Last Payroll Run', 'sub'=>$lastPayrollRun ? ucfirst($lastPayrollRun['status']) : 'None yet', 'link'=>'modules/payroll/post_salary.php'],
    ['icon'=>'ti-user-plus',    'cls'=>'green',  'val'=>number_format($joinedLast12),      'label'=>'Joined (Last 12 Months)',       'link'=>'modules/reports/stat_detail.php?type=joined_12m'],
    ['icon'=>'ti-user-minus',   'cls'=>'red',    'val'=>number_format($separatedLast12),   'label'=>'Separated (Last 12 Months)',    'link'=>'modules/reports/stat_detail.php?type=separated_12m'],
    ['icon'=>'ti-fingerprint',  'cls'=>'green',  'val'=>number_format($presentToday),      'label'=>'Present Today',                 'link'=>'modules/reports/stat_detail.php?type=present_today'],
    ['icon'=>'ti-beach',        'cls'=>'amber',  'val'=>number_format($onLeaveToday),      'label'=>'On Leave Today',                'link'=>'modules/reports/stat_detail.php?type=on_leave_today'],
];

// ── Charts / widgets data ────────────────────────────────────────

// 1. Last 6 months gross payroll trend
$payrollTrend = $db->fetchAll(
    "SELECT month, year, total_gross FROM payroll_runs WHERE $runOrgClause ORDER BY year DESC, month DESC LIMIT 6",
    $runOrgParams
);
$payrollTrend = array_reverse($payrollTrend);

// 2. Gender distribution
$genderRows = $db->fetchAll(
    "SELECT gender, COUNT(*) AS c FROM employees WHERE status='active' AND $empOrgClause GROUP BY gender",
    $empOrgParams
);
$genderMap = ['male'=>0,'female'=>0,'other'=>0];
foreach ($genderRows as $r) { $genderMap[$r['gender'] ?: 'other'] = (int)$r['c']; }

// 3. Years-in-service distribution
$serviceRows = $db->fetchAll(
    "SELECT date_of_joining FROM employees WHERE status='active' AND $empOrgClause",
    $empOrgParams
);
$serviceBuckets = ['0-1 yr'=>0, '1-3 yrs'=>0, '3-5 yrs'=>0, '5-10 yrs'=>0, '10+ yrs'=>0];
foreach ($serviceRows as $r) {
    $yrs = yearsOfService($r['date_of_joining']);
    if ($yrs < 1) $serviceBuckets['0-1 yr']++;
    elseif ($yrs < 3) $serviceBuckets['1-3 yrs']++;
    elseif ($yrs < 5) $serviceBuckets['3-5 yrs']++;
    elseif ($yrs < 10) $serviceBuckets['5-10 yrs']++;
    else $serviceBuckets['10+ yrs']++;
}

// 4. Count by category
$byCategory = $db->fetchAll(
    "SELECT c.name, COUNT(e.id) AS cnt FROM employees e
       JOIN categories c ON c.id=e.category_id
      WHERE e.status='active' AND $empOrgClauseE
      GROUP BY c.name ORDER BY cnt DESC",
    $empOrgParamsE
);

// 5. Count by department
$byDept = $db->fetchAll(
    "SELECT d.name, COUNT(e.id) AS cnt FROM employees e
       JOIN departments d ON d.id=e.department_id
      WHERE e.status='active' AND $empOrgClauseE
      GROUP BY d.name ORDER BY cnt DESC",
    $empOrgParamsE
);

// 6. Age distribution
$ageRows = $db->fetchAll(
    "SELECT date_of_birth FROM employees WHERE status='active' AND date_of_birth IS NOT NULL AND $empOrgClause",
    $empOrgParams
);
$ageBuckets = ['<25'=>0, '25-35'=>0, '35-45'=>0, '45-55'=>0, '55+'=>0];
foreach ($ageRows as $r) {
    $age = calcAge($r['date_of_birth']);
    if ($age < 25) $ageBuckets['<25']++;
    elseif ($age < 35) $ageBuckets['25-35']++;
    elseif ($age < 45) $ageBuckets['35-45']++;
    elseif ($age < 55) $ageBuckets['45-55']++;
    else $ageBuckets['55+']++;
}

// 7. Headcount trend — active headcount at the end of each of the last 12 months
$headcountTrend = [];
for ($i = 11; $i >= 0; $i--) {
    $asOf = (new DateTime())->modify("-$i months")->format('Y-m-t'); // last day of that month
    $count = (int)$db->fetchValue(
        "SELECT COUNT(*) FROM employees e
          WHERE e.date_of_joining <= ? AND $empOrgClauseE
            AND (e.status='active' OR NOT EXISTS (
                    SELECT 1 FROM separations s WHERE s.employee_id=e.id AND s.last_working_date <= ?
                 ))",
        array_merge([$asOf], $empOrgParamsE, [$asOf])
    );
    $headcountTrend[] = ['label' => (new DateTime($asOf))->format('M Y'), 'count' => $count];
}

// 8. Count by designation
$byDesignation = $db->fetchAll(
    "SELECT des.name, COUNT(e.id) AS cnt FROM employees e
       JOIN designations des ON des.id=e.designation_id
      WHERE e.status='active' AND $empOrgClauseE
      GROUP BY des.name ORDER BY cnt DESC LIMIT 10",
    $empOrgParamsE
);

// 9. Work anniversaries in the next 30 days
$workAnniversaries = $db->fetchAll(
    "SELECT employee_id, first_name, last_name, date_of_joining,
            DATE_ADD(date_of_joining, INTERVAL (YEAR(CURDATE()) - YEAR(date_of_joining) + IF(DAYOFYEAR(date_of_joining) < DAYOFYEAR(CURDATE()), 1, 0)) YEAR) AS next_anniv
       FROM employees
      WHERE status='active' AND $empOrgClause
     HAVING next_anniv BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
      ORDER BY next_anniv",
    $empOrgParams
);

// 10. Birthdays in the next 30 days
$birthdays = $db->fetchAll(
    "SELECT employee_id, first_name, last_name, date_of_birth,
            DATE_ADD(date_of_birth, INTERVAL (YEAR(CURDATE()) - YEAR(date_of_birth) + IF(DAYOFYEAR(date_of_birth) < DAYOFYEAR(CURDATE()), 1, 0)) YEAR) AS next_bday
       FROM employees
      WHERE status='active' AND date_of_birth IS NOT NULL AND $empOrgClause
     HAVING next_bday BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
      ORDER BY next_bday",
    $empOrgParams
);

// 11. Wedding anniversaries in the next 30 days
$weddingAnniversaries = $db->fetchAll(
    "SELECT employee_id, first_name, last_name, marriage_anniversary_date,
            DATE_ADD(marriage_anniversary_date, INTERVAL (YEAR(CURDATE()) - YEAR(marriage_anniversary_date) + IF(DAYOFYEAR(marriage_anniversary_date) < DAYOFYEAR(CURDATE()), 1, 0)) YEAR) AS next_anniv
       FROM employees
      WHERE status='active' AND marriage_anniversary_date IS NOT NULL AND $empOrgClause
     HAVING next_anniv BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
      ORDER BY next_anniv",
    $empOrgParams
);

include __DIR__ . '/includes/header.php';
?>

<!-- 8 Stat Cards -->
<div class="row g-3 mb-4">
  <?php foreach ($stats as $s): ?>
  <div class="col-6 col-md-4 col-xl-3">
    <a href="<?= BASE_URL ?>/<?= $s['link'] ?>" class="text-decoration-none">
      <div class="pc-stat d-flex align-items-start gap-3 h-100">
        <div class="pc-stat-icon <?= $s['cls'] ?>"><i class="ti <?= $s['icon'] ?>"></i></div>
        <div>
          <div class="pc-stat-val"><?= $s['val'] ?></div>
          <div class="pc-stat-label"><?= $s['label'] ?></div>
          <?php if (isset($s['sub'])): ?><div style="font-size:10px;color:var(--pc-text2)"><?= clean($s['sub']) ?></div><?php endif; ?>
        </div>
      </div>
    </a>
  </div>
  <?php endforeach; ?>
</div>

<!-- Charts row 1 -->
<div class="row g-3 mb-3">
  <div class="col-md-6">
    <div class="pc-card h-100">
      <div class="pc-card-title">Last 6 Months Gross Payroll</div>
      <canvas id="payrollChart" height="110"></canvas>
    </div>
  </div>
  <div class="col-md-3">
    <div class="pc-card h-100">
      <div class="pc-card-title">Gender Distribution</div>
      <canvas id="genderChart" height="110"></canvas>
    </div>
  </div>
  <div class="col-md-3">
    <div class="pc-card h-100">
      <div class="pc-card-title">Years in Service</div>
      <canvas id="serviceChart" height="110"></canvas>
    </div>
  </div>
</div>

<!-- Charts row 2 -->
<div class="row g-3 mb-3">
  <div class="col-md-4">
    <div class="pc-card h-100">
      <div class="pc-card-title">Employee Count by Category</div>
      <canvas id="categoryChart" height="130"></canvas>
    </div>
  </div>
  <div class="col-md-4">
    <div class="pc-card h-100">
      <div class="pc-card-title">Employee Count by Department</div>
      <canvas id="deptChart" height="130"></canvas>
    </div>
  </div>
  <div class="col-md-4">
    <div class="pc-card h-100">
      <div class="pc-card-title">Age Distribution</div>
      <canvas id="ageChart" height="130"></canvas>
    </div>
  </div>
</div>

<!-- Charts row 3 -->
<div class="row g-3 mb-3">
  <div class="col-md-6">
    <div class="pc-card h-100">
      <div class="pc-card-title">Employee Headcount — Last 12 Months</div>
      <canvas id="headcountChart" height="100"></canvas>
    </div>
  </div>
  <div class="col-md-6">
    <div class="pc-card h-100">
      <div class="pc-card-title">Employee Count by Designation</div>
      <canvas id="designationChart" height="100"></canvas>
    </div>
  </div>
</div>

<!-- Anniversary / Birthday lists -->
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card h-100">
      <div class="pc-card-title"><i class="ti ti-briefcase me-1"></i>Work Anniversaries — Next 30 Days</div>
      <?php if (!$workAnniversaries): ?>
        <div class="text-muted small text-center py-3">None coming up</div>
      <?php endif; ?>
      <?php foreach ($workAnniversaries as $w):
          $yrs = (int)round((strtotime($w['next_anniv']) - strtotime($w['date_of_joining'])) / (365.25*86400));
      ?>
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div>
          <div class="small fw-semibold"><?= clean($w['first_name'].' '.$w['last_name']) ?></div>
          <div class="text-muted" style="font-size:10px"><?= clean($w['employee_id']) ?> · <?= fmtDate($w['next_anniv']) ?></div>
        </div>
        <span class="badge bg-primary"><?= $yrs ?> yrs</span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <div class="col-md-4">
    <div class="pc-card h-100">
      <div class="pc-card-title"><i class="ti ti-cake me-1"></i>Birthdays — Next 30 Days</div>
      <?php if (!$birthdays): ?>
        <div class="text-muted small text-center py-3">None coming up</div>
      <?php endif; ?>
      <?php foreach ($birthdays as $b): ?>
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div>
          <div class="small fw-semibold"><?= clean($b['first_name'].' '.$b['last_name']) ?></div>
          <div class="text-muted" style="font-size:10px"><?= clean($b['employee_id']) ?></div>
        </div>
        <span class="badge bg-info"><?= fmtDate($b['next_bday'], 'd M') ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <div class="col-md-4">
    <div class="pc-card h-100">
      <div class="pc-card-title"><i class="ti ti-heart me-1"></i>Wedding Anniversaries — Next 30 Days</div>
      <?php if (!$weddingAnniversaries): ?>
        <div class="text-muted small text-center py-3">None coming up</div>
      <?php endif; ?>
      <?php foreach ($weddingAnniversaries as $wa): ?>
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div>
          <div class="small fw-semibold"><?= clean($wa['first_name'].' '.$wa['last_name']) ?></div>
          <div class="text-muted" style="font-size:10px"><?= clean($wa['employee_id']) ?></div>
        </div>
        <span class="badge bg-danger"><?= fmtDate($wa['next_anniv'], 'd M') ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<?php
$payrollLabels = array_map(fn($p) => monthName((int)$p['month']).' '.substr((string)$p['year'],2), $payrollTrend);
$payrollGross  = array_map(fn($p) => round($p['total_gross']/100000, 2), $payrollTrend);

$extraJs = "
<script src='https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js'></script>
<script>
new Chart(document.getElementById('payrollChart'), {
  type:'bar',
  data:{ labels:" . json_encode($payrollLabels) . ", datasets:[{ label:'Gross (₹ Lakhs)', data:" . json_encode($payrollGross) . ", backgroundColor:'rgba(26,95,122,0.2)', borderColor:'#1a5f7a', borderWidth:2, borderRadius:6 }] },
  options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true}}}
});

new Chart(document.getElementById('genderChart'), {
  type:'doughnut',
  data:{ labels:['Male','Female','Other'], datasets:[{ data:" . json_encode(array_values($genderMap)) . ", backgroundColor:['#2563eb','#db2777','#9333ea'] }] },
  options:{responsive:true,plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:10}}}}}
});

new Chart(document.getElementById('serviceChart'), {
  type:'doughnut',
  data:{ labels:" . json_encode(array_keys($serviceBuckets)) . ", datasets:[{ data:" . json_encode(array_values($serviceBuckets)) . ", backgroundColor:['#16a34a','#2563eb','#d97706','#7c3aed','#dc2626'] }] },
  options:{responsive:true,plugins:{legend:{position:'bottom',labels:{boxWidth:10,font:{size:10}}}}}
});

new Chart(document.getElementById('categoryChart'), {
  type:'bar',
  data:{ labels:" . json_encode(array_column($byCategory,'name')) . ", datasets:[{ label:'Employees', data:" . json_encode(array_map('intval',array_column($byCategory,'cnt'))) . ", backgroundColor:'#1a5f7a', borderRadius:4 }] },
  options:{responsive:true,indexAxis:'y',plugins:{legend:{display:false}},scales:{x:{beginAtZero:true}}}
});

new Chart(document.getElementById('deptChart'), {
  type:'bar',
  data:{ labels:" . json_encode(array_column($byDept,'name')) . ", datasets:[{ label:'Employees', data:" . json_encode(array_map('intval',array_column($byDept,'cnt'))) . ", backgroundColor:'#2563eb', borderRadius:4 }] },
  options:{responsive:true,indexAxis:'y',plugins:{legend:{display:false}},scales:{x:{beginAtZero:true}}}
});

new Chart(document.getElementById('ageChart'), {
  type:'bar',
  data:{ labels:" . json_encode(array_keys($ageBuckets)) . ", datasets:[{ label:'Employees', data:" . json_encode(array_values($ageBuckets)) . ", backgroundColor:'#d97706', borderRadius:4 }] },
  options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true}}}
});

new Chart(document.getElementById('headcountChart'), {
  type:'line',
  data:{ labels:" . json_encode(array_column($headcountTrend,'label')) . ", datasets:[{ label:'Headcount', data:" . json_encode(array_column($headcountTrend,'count')) . ", borderColor:'#16a34a', backgroundColor:'rgba(22,163,74,0.1)', fill:true, tension:0.3 }] },
  options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true}}}
});

new Chart(document.getElementById('designationChart'), {
  type:'bar',
  data:{ labels:" . json_encode(array_column($byDesignation,'name')) . ", datasets:[{ label:'Employees', data:" . json_encode(array_map('intval',array_column($byDesignation,'cnt'))) . ", backgroundColor:'#7c3aed', borderRadius:4 }] },
  options:{responsive:true,indexAxis:'y',plugins:{legend:{display:false}},scales:{x:{beginAtZero:true}}}
});
</script>";
include __DIR__ . '/includes/footer.php';