<?php
require 'config/db.php';

$month    = $_GET['month'] ?? date('n');
$year     = $_GET['year'] ?? date('Y');
$sales_id = $_GET['sales_id'] ?? '';

$emps = $pdo->query("SELECT id, full_name FROM sales_employees ORDER BY full_name")->fetchAll(PDO::FETCH_ASSOC);

function fetchKPI($pdo,$table,$sales_id,$month,$year){
    $stmt = $pdo->prepare("SELECT * FROM $table WHERE sales_id=? AND month=? AND year=?");
    $stmt->execute([$sales_id,$month,$year]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

$behavior  = $sales_id ? fetchKPI($pdo,'sales_behavior_kpi',$sales_id,$month,$year) : null;
$quality   = $sales_id ? fetchKPI($pdo,'sale_quality_kpi',$sales_id,$month,$year) : null;
$objective = $sales_id ? fetchKPI($pdo,'sales_objective_kpi',$sales_id,$month,$year) : null;

/* ===== SCORE FUNCTIONS ===== */
function percentScore($p){ return ($p>=100)?10:round($p/10,1); }
function dealScore($d){ return ($d>=10)?10:max(0,$d); }
function newClientScore($v){ return min(10,2+$v); }
function difficultSaleScore($v){ return min(10,($v*2)+1); }
function strategyScore($v){
    if($v==1) return 4;
    if($v==2) return 7;
    if($v==3) return 9;
    if($v>=4) return 10;
    return 0;
}

/* ===== KPI ARRAYS ===== */
$behaviorScores = $behavior ? [
    ['CRM Discipline',    $behavior['CRM_discipline'],3,'#1E90FF'],
    ['Attendance',        $behavior['attendance'],6,'#E63946'],
    ['Punctuality',       $behavior['punctuality'],4,'#2ECC71'],
    ['Overtime',          $behavior['overtime'],4,'#F77F00'],
    ['Team Coordination', $behavior['team_coordination'],3,'#FCA311']
] : [];

$qualityScores = $quality ? [
    ['New Clients',     newClientScore($quality['new_clients']),10,'#6A4C93'],
    ['Difficult Sales', difficultSaleScore($quality['difficult_sales']),10,'#FF6F91'],
    ['New Strategy',    strategyScore($quality['new_sale_strategy']),10,'#8D5524']
] : [];

$objectiveScores = $objective ? [
    ['Team Contribution', percentScore($objective['team_target_contribution']),10,'#2A9D8F'],
    ['Team Division',     percentScore($objective['percent_team_target_division']),10,'#3A0CA3'],
    ['Individual Target', percentScore($objective['percent_individual_target']),10,'#00B4D8'],
    ['Qualified Deals',   dealScore($objective['qualified_deals']),10,'#6B8E23'],
    ['Payments Received',percentScore($objective['percent_received_payments']),10,'#E9C46A']
] : [];

$behaviorTotal  = array_sum(array_column($behaviorScores,1));
$qualityTotal   = array_sum(array_column($qualityScores,1));
$objectiveTotal = array_sum(array_column($objectiveScores,1));
$overall        = $behaviorTotal + $qualityTotal + $objectiveTotal;

/* ===== DONUT DATA ===== */
$donutLabels = [];
$donutData   = [];
$donutColors = [];

foreach([$behaviorScores,$qualityScores,$objectiveScores] as $group){
    foreach($group as $g){
        $donutLabels[] = $g[0];
        $donutData[]   = $g[1];
        $donutColors[] = $g[3];
    }
}

include 'assets/layout_top.php';
?>
<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/png" href="images/jg.webp">
<title>JG - Suite</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>

.container{
    max-width:1350px;
    margin:30px auto;
}

/* ==== GLASS CARD STYLE ==== */
.card{
    background:rgba(255,255,255,0.05);
    backdrop-filter:blur(10px);
    padding:26px 28px;
    border-radius:18px;
    margin-bottom:26px;
    color:white;
    box-shadow:0 12px 30px rgba(0,0,0,.6);
    border:1px solid rgba(255,255,255,0.1);
    z-index: 10;
}

/* GRID */
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:20px; z-index: 10;}

h2{margin-bottom:15px}
.progress{
    height:10px;
    background:rgba(255,255,255,0.1);
    border-radius:999px;
    overflow:hidden;
}
.bar{
    height:100%;
    border-radius:999px;
    box-shadow:0 0 12px rgba(255,255,255,0.3);
}
.item{
    padding:12px 14px;
    border-radius:12px;
    background:rgba(255,255,255,0.08);
    margin-bottom:12px;
    border:1px solid rgba(255,255,255,0.1);
}
.kpi-total{
    margin-top:12px;
    font-weight:700;
    font-size:15px;
    text-align:right;
    color:#fff;
}
select,input,button{
    padding:10px;
    width:100%;
    margin:6px 0;
    border-radius:10px;
    border:none;
    background:rgba(255,255,255,0.1);
    color:#fff;
}
button{background:#1f8cff;color:#fff;cursor:pointer}

/* SPEEDOMETER */
.section{
    position:relative;
    padding:40px 50px 45px;
    border-radius:18px;
    background:rgba(255,255,255,0.05);
    backdrop-filter:blur(12px);
    box-shadow:0 25px 60px rgba(0,0,0,0.7);
    overflow:hidden;
}

/* ===== SPEEDOMETER ===== */
.speedometer{
    width:360px;
    height:200px;
    position:relative;
    overflow:hidden;
    margin:auto;
}

.arc{
    width:360px;
    height:360px;
    border-radius:50%;
    background:
      conic-gradient(
        from 180deg,
        #ee6d22,
        #e85900,
        #0374b5 180deg
      );
    position:absolute;
    bottom:-160px;
    border:3px solid #000000;
}

/* Numbers */
.number{
    position:absolute;
    font-size:15px;
    color:white;
    font-weight:600;
}

/* Needle */
.needle{
    position:absolute;
    width:4px;
    height:150px;
    background:linear-gradient(to top,#ef4444,#fecaca);
    left:50%;
    bottom:20px;
    transform-origin:bottom center;
    transform:rotate(-90deg);
    transition:transform 1.2s cubic-bezier(.22,1,.36,1);
    box-shadow:0 0 16px red;
    border-radius:3px;
}

.center{
    width:20px;
    height:20px;
    background:#fff;
    border-radius:50%;
    position:absolute;
    left:50%;
    bottom:10px;
    transform:translateX(-50%);
    z-index:5;
}

/* Digital */
.digital{
    margin-top:18px;
    font-size:34px;
    font-weight:700;
    color:white;
    text-shadow:0 0 12px rgba(255, 255, 255, 0.8);
}

/* Controls */
.controls{
    margin-top:24px;
    display:flex;
    justify-content:center;
    gap:12px;
}
.master{
    display:flex;
 justify-content:space-around;
 z-index: 10;
}

</style>
</head>
<body>
    <br><br>
<div class="container">
<div class="master">
<!-- FILTER -->
<div class="card">
<form>
<select name="sales_id" required>
<option value="">Select Employee</option>
<?php foreach($emps as $e): ?>
<option value="<?= $e['id'] ?>" <?=($sales_id==$e['id'])?'selected':''?>><?= $e['full_name'] ?></option>
<?php endforeach ?>
</select>
<input type="number" name="month" value="<?= $month ?>" min="1" max="12">
<input type="number" name="year" value="<?= $year ?>">
<button>View KPI</button>
</form>
</div>

<?php if($sales_id): ?>
<!-- SPEEDOMETER -->
<div class="card section">
<div class="speedometer">
<div class="arc" id="arc"></div>
<div class="needle" id="needle"></div>
<div class="center"></div>
</div>
<div class="digital" id="digital">0 / 100</div>
</div>
</div>
<!-- OVERALL KPI -->
<div class="card grid">
<div>
<h2>Overall KPI</h2>
<div class="total"><?= $overall ?>/100</div>
<p>Behavior: <?= $behaviorTotal ?>/20</p>
<p>Quality: <?= $qualityTotal ?>/30</p>
<p>Objective: <?= $objectiveTotal ?>/50</p>
</div>
<div>
<canvas id="donut"></canvas>
</div>
<div>
<p><b>Performance Level:</b><br>
<?= ($overall>=85?'Excellent ⭐':($overall>=70?'Good 👍':($overall>=50?'Average ⚠️':'Poor ❌'))) ?>
</p>
</div>
</div>
<br>
<!-- BEHAVIOR -->
<div class="card">
<h2>Behavior KPI</h2>
<?php foreach($behaviorScores as $v): ?>
<div class="item">
<div style="display:flex;justify-content:space-between;font-weight:600;color:#fff">
<span><?= $v[0] ?></span>
<span><?= $v[1] ?> / <?= $v[2] ?></span>
</div>
<div class="progress">
<div class="bar" style="width:<?= ($v[1]/$v[2])*100 ?>%;background:<?= $v[3] ?>"></div>
</div>
</div>
<?php endforeach; ?>
<div class="kpi-total">Total: <?= $behaviorTotal ?>/20</div>
</div>

<!-- QUALITY -->
<div class="card">
<h2>Quality KPI</h2>
<?php foreach($qualityScores as $v): ?>
<div class="item">
<div style="display:flex;justify-content:space-between;font-weight:600;color:#fff">
<span><?= $v[0] ?></span>
<span><?= $v[1] ?> / <?= $v[2] ?></span>
</div>
<div class="progress">
<div class="bar" style="width:<?= ($v[1]/$v[2])*100 ?>%;background:<?= $v[3] ?>"></div>
</div>
</div>
<?php endforeach; ?>
<div class="kpi-total">Total: <?= $qualityTotal ?>/30</div>
</div>

<!-- OBJECTIVE -->
<div class="card">
<h2>Objective KPI</h2>
<?php foreach($objectiveScores as $v): ?>
<div class="item">
<div style="display:flex;justify-content:space-between;font-weight:600;color:#fff">
<span><?= $v[0] ?></span>
<span><?= $v[1] ?> / <?= $v[2] ?></span>
</div>
<div class="progress">
<div class="bar" style="width:<?= ($v[1]/$v[2])*100 ?>%;background:<?= $v[3] ?>"></div>
</div>
</div>
<?php endforeach; ?>
<div class="kpi-total">Total: <?= $objectiveTotal ?>/50</div>
</div>
<?php endif; ?>
</div>

<script>
new Chart(document.getElementById('donut'),{
type:'doughnut',
data:{
labels: <?= json_encode($donutLabels) ?>,
datasets:[{
data: <?= json_encode($donutData) ?>,
backgroundColor: <?= json_encode($donutColors) ?>
}]
},
options:{
cutout:'65%',
plugins:{legend:{position:'bottom',labels:{color:'#fff'}}}
}
});

/* SPEEDOMETER NUMBERS */
const arc = document.getElementById("arc");
for(let i=0;i<=100;i+=10){
    const num = document.createElement("div");
    num.className = "number";
    num.innerText = i;
    const angle = (-180 + (i * 180 / 100)) * Math.PI / 180;
    const r = 150;
    const cx = 180;
    const cy = 180;
    num.style.left = (cx + r * Math.cos(angle) - 12) + "px";
    num.style.top  = (cy + r * Math.sin(angle) - 12) + "px";
    arc.appendChild(num);
}

/* KPI → SPEEDOMETER */
let kpiScore = <?= (int)$overall ?>;
const angle = -90 + (kpiScore * 180 / 100);
document.getElementById("needle").style.transform = `rotate(${angle}deg)`;
document.getElementById("digital").innerText = kpiScore + " / 100";
</script>
</body>
</html>
<?php
/* ===== LAYOUT END ===== */
include 'assets/layout_bottom.php';
?>