<?php
require 'config/db.php';
session_start();
require 'sync_achievements.php'; // Auto update

$month = date('Y-m-01');

// TEAM
$team = $pdo->query("SELECT target_value, achieved_amount, completed FROM team_targets WHERE target_month='$month'")->fetch();

// INDIVIDUAL with ranking
$employees = $pdo->query("
    SELECT se.full_name, it.target_value, it.achieved_amount, it.contribution, it.completed
    FROM individual_targets it
    JOIN sales_employees se ON se.id = it.sales_employee_id
    WHERE it.target_month='$month'
    ORDER BY it.achieved_amount DESC
")->fetchAll();

function percent($ach, $target){ return $target>0 ? min(100, round(($ach/$target)*100)) : 0; }
?>
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/png" href="images/jg.webp">
<title>JG - Suite</title>>
<style>
body{font-family:Arial;background:#f4f6f9}
.container{width:90%;margin:40px auto}
.card{background:#fff;padding:20px;border-radius:12px;box-shadow:0 5px 20px rgba(0,0,0,.08);margin-bottom:25px}
.progress{background:#e5e7eb;border-radius:10px;height:16px;margin-top:5px}
.bar{background:#22c55e;height:100%}
table{width:100%;border-collapse:collapse;margin-top:10px}
th,td{padding:10px;border-bottom:1px solid #eee;text-align:left}
.completed{color:green;font-weight:bold}
</style>
</head>
<body>
<div class="container">

<div class="card">
<h2>📊 Team Target (<?= date('F Y') ?>)</h2>
<p>Target: <?= number_format($team['target_value']??0) ?></p>
<p>Achieved: <?= number_format($team['achieved_amount']??0) ?> 
<?php if($team['completed']) echo "<span class='completed'>(Completed)</span>"; ?></p>
<div class="progress"><div class="bar" style="width:<?= percent($team['achieved_amount']??0,$team['target_value']??0) ?>%"></div></div>
</div>

<div class="card">
<h2>👤 Individual KPI (Ranking by Achieved Amount)</h2>
<table>
<tr><th>Rank</th><th>Name</th><th>Target</th><th>Achieved</th><th>Contribution</th><th>Status</th><th>Progress</th></tr>
<?php $rank=1; foreach($employees as $e): ?>
<tr>
<td><?= $rank++ ?></td>
<td><?= htmlspecialchars($e['full_name']) ?></td>
<td><?= number_format($e['target_value']) ?></td>
<td><?= number_format($e['achieved_amount']) ?></td>
<td><?= number_format($e['contribution']) ?></td>
<td><?= $e['completed']? "<span class='completed'>Completed</span>":"In Progress" ?></td>
<td>
<div class="progress"><div class="bar" style="width:<?= percent($e['achieved_amount'],$e['target_value']) ?>%"></div></div>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>

</div>
</body>
</html>
