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

/* ===== MONTH / YEAR ===== */
$month = $_POST['month'] ?? date('n');
$year  = $_POST['year'] ?? date('Y');

/* ===== DESIGNERS ===== */
$designers = $pdo->query("
    SELECT id, full_name 
    FROM design_employees 
    ORDER BY full_name
")->fetchAll(PDO::FETCH_ASSOC);

/* ================= CALCULATE ALL KPI ================= */
if(isset($_POST['save_all'])){

    $designer_id   = $_POST['designer_id'];
    $designer_name = $_POST['designer_name'];

    /* ===================================================
       PROJECTS (COMPLETED)
    =================================================== */
    $stmt = $pdo->prepare("
        SELECT id, price, tip_amount, deadline, revision_count
        FROM projects
        WHERE designer_id=?
        AND MONTH(created_at)=?
        AND YEAR(created_at)=?
        AND status='Completed'
    ");
    $stmt->execute([$designer_id,$month,$year]);
    $projects = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $totalProjects   = count($projects);
    $tipPercents     = [];
    $tippedProjects  = 0;
    $onTimeDelivered = 0;
    $totalRevisions  = 0;

    foreach($projects as $p){

        /* TIP % */
        if($p['tip_amount'] > 0 && $p['price'] > 0){
            $tipPercents[] = ($p['tip_amount']/$p['price']) * 100;
            $tippedProjects++;
        }

        /* REVISIONS */
        $totalRevisions += (float)$p['revision_count'];

        /* FINAL UPLOAD */
        $act = $pdo->prepare("
            SELECT created_at FROM project_actions
            WHERE project_id=? AND action='Final files uploaded'
            ORDER BY created_at DESC LIMIT 1
        ");
        $act->execute([$p['id']]);
        $finalUpload = $act->fetchColumn();

        if($finalUpload && strtotime($finalUpload) <= strtotime($p['deadline'])){
            $onTimeDelivered++;
        }
    }

    /* ===================================================
       QUALITY KPI (25)
    =================================================== */
    $avgTip = $tipPercents ? array_sum($tipPercents)/count($tipPercents) : 0;

    if($avgTip>=30) $avgTipScore=15;
    elseif($avgTip>=25) $avgTipScore=12;
    elseif($avgTip>=20) $avgTipScore=9;
    elseif($avgTip>=15) $avgTipScore=6;
    elseif($avgTip>=10) $avgTipScore=3;
    else $avgTipScore=0;

    $tipRatio = ($totalProjects>0)?($tippedProjects/$totalProjects*100):0;
    if($tipRatio>=80) $tipRatioScore=5;
    elseif($tipRatio>=60) $tipRatioScore=4;
    elseif($tipRatio>=40) $tipRatioScore=3;
    elseif($tipRatio>=20) $tipRatioScore=2;
    elseif($tipRatio>0)  $tipRatioScore=1;
    else $tipRatioScore=0;

    $qualityOnTime = ($totalProjects>0 && $onTimeDelivered==$totalProjects)?5:0;

    $totalQuality = $avgTipScore + $tipRatioScore + $qualityOnTime;

    /* ===================================================
       OBJECTIVE KPI (75)
    =================================================== */

    /* REVISION SCORE (15) */
    $avgRevision = ($totalProjects>0)?($totalRevisions/$totalProjects):0;

    if($avgRevision==0) $revisionScore=15;
    elseif($avgRevision<=1) $revisionScore=10;
    elseif($avgRevision<=1.5) $revisionScore=8;
    elseif($avgRevision<=2) $revisionScore=6;
    elseif($avgRevision<=2.5) $revisionScore=4;
    elseif($avgRevision<=3) $revisionScore=2;
    else $revisionScore=0;

    /* ON TIME DELIVERY (25) */
    $onTimePercent = ($totalProjects>0)?($onTimeDelivered/$totalProjects*100):0;
    if($onTimePercent>=95) $onTimeScore=25;
    elseif($onTimePercent>=90) $onTimeScore=20;
    elseif($onTimePercent>=85) $onTimeScore=15;
    elseif($onTimePercent>=80) $onTimeScore=10;
    elseif($onTimePercent>=75) $onTimeScore=5;
    else $onTimeScore=0;

    /* PROCESS KPI (10) */
    $assigned = $pdo->prepare("
        SELECT COUNT(*) FROM projects
        WHERE designer_id=? AND MONTH(created_at)=? AND YEAR(created_at)=?
    ");
    $assigned->execute([$designer_id,$month,$year]);
    $assignedCount = $assigned->fetchColumn();

    $done = $pdo->prepare("
        SELECT COUNT(*) FROM projects
        WHERE designer_id=? AND MONTH(created_at)=? AND YEAR(created_at)=?
        AND status IN ('Completed','Final files uploaded')
    ");
    $done->execute([$designer_id,$month,$year]);
    $doneCount = $done->fetchColumn();

    $compliance = ($assignedCount>0)?($doneCount/$assignedCount*100):0;
    if($compliance>=95) $processScore=10;
    elseif($compliance>=90) $processScore=8;
    elseif($compliance>=85) $processScore=6;
    else $processScore=4;

    $totalObjective = $onTimeScore + $revisionScore + $processScore;

    /* ===================================================
       BEHAVIOR KPI (25)
    =================================================== */
   
    
    /* ===================================================
       SAVE ALL TABLES
    =================================================== */
    $pdo->prepare("
        REPLACE INTO design_objective_kpi
        (designer_id,designer_name,month,year,on_time_delivery,revisions,process,total_objective)
        VALUES (?,?,?,?,?,?,?,?)
    ")->execute([$designer_id,$designer_name,$month,$year,$onTimeScore,$revisionScore,$processScore,$totalObjective]);

    $pdo->prepare("
        REPLACE INTO design_quality_kpi
        (designer_id,designer_name,month,year,avg_tip_score,tip_ratio_score,ontime_score,total_quality)
        VALUES (?,?,?,?,?,?,?,?)
    ")->execute([$designer_id,$designer_name,$month,$year,$avgTipScore,$tipRatioScore,$qualityOnTime,$totalQuality]);

    

    $msg_all = "✅ KPI Auto Calculated Successfully";
}
?>
<?php include 'assets/header.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Designer KPI</title>
<style>
body{font-family:Arial;background:#f1f5f9; padding:20px;}
.box{max-width:1000px;margin:30px auto;background:#fff;padding:25px;border-radius:14px}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:15px}
.card{background:#f8fafc;padding:18px;border-radius:12px;text-align:center}
h3{margin:0;color:#475569}
p{font-size:26px;font-weight:bold;margin:6px 0}
button{padding:10px 18px;background:#2563eb;color:#fff;border:none;border-radius:8px}
</style>
</head>

<body>
    <br><br>
    <canvas id="particles"></canvas>
<div class="box glass">
<form method="post">
<select name="designer_id" required onchange="this.form.designer_name.value=this.options[this.selectedIndex].text">
<option value="">Select Designer</option>
<?php foreach($designers as $d): ?>
<option value="<?=$d['id']?>"><?=$d['full_name']?></option>
<?php endforeach ?>
</select>
<input type="hidden" name="designer_name">

<input type="number" name="month" value="<?=$month?>">
<input type="number" name="year" value="<?=$year?>">

<button name="save_all">Calculate KPI</button>
</form>

<?= $msg_all ?? '' ?>

</div>
</body>
</html>
<?php
require 'config/db.php';

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

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

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

$objective = $designer_id ? fetchKPI($pdo,'design_objective_kpi',$designer_id,$month,$year) : null;
$quality   = $designer_id ? fetchKPI($pdo,'design_quality_kpi',$designer_id,$month,$year) : null;
$behavior  = $designer_id ? fetchKPI($pdo,'design_behavior_kpi',$designer_id,$month,$year) : null;

/* ================= KPI ARRAYS ================= */

$objectiveScores = $objective ? [
    ['On Time Delivery', $objective['on_time_delivery'],25,'#06b6d4'],
    ['Revisions',        $objective['revisions'],15,'#f97316'],
    ['Process',          $objective['process'],10,'#22c55e']
] : [];

$qualityScores = $quality ? [
    ['Avg Tip Score', $quality['avg_tip_score'],15,'#8b5cf6'],
    ['Tip Ratio',     $quality['tip_ratio_score'],5,'#ec4899'],
    ['On Time Ratio',   $quality['ontime_score'],5,'#0ea5e9']
] : [];

$behaviorScores = $behavior ? [
    ['Punctuality',       $behavior['punctuality'],4,'#22c55e'],
    ['Attendance',        $behavior['attendance'],6,'#3b82f6'],
    ['Communication',     $behavior['communication'],3,'#a855f7'],
    ['Team Coordination', $behavior['team_coordination'],3,'#f59e0b'],
    ['Overtime',          $behavior['overtime'],4,'#ef4444'],
    ['CRM Discipline',    $behavior['crm_discipline'],3,'#14b8a6'],
    ['Professionalism',   $behavior['professionalism'],2,'#6366f1']
] : [];

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

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

foreach([$objectiveScores,$qualityScores,$behaviorScores] as $group){
    foreach($group as $g){
        $donutLabels[] = $g[0];
        $donutData[]   = $g[1];
        $donutColors[] = $g[3];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Designer KPI Dashboard</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
body{
    margin:0;
    font-family: "Segoe UI", Arial, sans-serif;
    background: linear-gradient(135deg,#050814,#0b0f1a);
    color:#fff;
    min-height:100vh;
}

.mesh{
    position:fixed; inset:0;
    background:
        radial-gradient(circle at 15% 20%, rgba(31,140,255,.25), transparent 45%),
        radial-gradient(circle at 80% 25%, rgba(255,138,0,.25), transparent 45%),
        linear-gradient(180deg,#03040a,#070b18);
    animation: hue 30s linear infinite;
    z-index:-5;
}
@keyframes hue{100%{filter:hue-rotate(30deg)}}

.grid-bg{
  position:fixed; inset:0;
  background:
    linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px);
  background-size:70px 70px;
  animation:grid 50s linear infinite;
  z-index:-1;
}
@keyframes grid{to{transform:translateY(70px)}}

.glass{
    max-width:1400px;
    margin:40px auto;
    padding:30px;
    background:rgba(255,255,255,.06);
    backdrop-filter:blur(18px);
    border-radius:20px;
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 20px 45px rgba(0,0,0,.45);
}

.card{
    background:rgba(255,255,255,.07);
    padding:24px;
    border-radius:18px;
    margin-bottom:22px;
    border:none;
    color:#fff;
    box-shadow:0 10px 30px rgba(0,0,0,.35);
}

.grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:20px
}

.progress{
    height:12px;
    background:rgba(255,255,255,.15);
    border-radius:10px;
    overflow:hidden
}

.bar{
    height:100%;
    border-radius:10px
}

.item{margin-bottom:14px}

.total{font-size:32px;font-weight:800}

select,input,button{
    padding:10px;
    width:100%;
    margin:6px 0;
    border-radius:10px;
    border:1px solid rgba(255,255,255,.2);
    background:rgba(255,255,255,.08);
    color:#fff;
}

button{
    background:#f59e0b;
    border:none;
    font-weight:600
}

h2{margin-bottom:12px}
</style>
</head>

<body>

<div class="mesh"></div>
<div class="grid-bg"></div>



<div class="glass">

<!-- FILTER -->
<div class="card">
<form>
<select name="designer_id" required>
<option value="">Select Designer</option>
<?php foreach($designers as $d): ?>
<option value="<?=$d['id']?>" <?=($designer_id==$d['id'])?'selected':''?>>
    <?=$d['full_name']?>
</option>
<?php endforeach ?>
</select>

<input type="number" name="month" value="<?=$month?>">
<input type="number" name="year" value="<?=$year?>">

<button>View KPI</button>
</form>
</div>

<?php if($designer_id): ?>

<!-- OVERALL -->
<div class="card grid">

<div>
<h2>Overall KPI</h2>
<div class="total"><?=$overall?> / 125</div>
<p>Objective: <?=$objectiveTotal?> / 50</p>
<p>Quality: <?=$qualityTotal?> / 25</p>
<p>Behavior: <?=$behaviorTotal?> / 25</p>
</div>

<div>
<canvas id="donut"></canvas>
</div>

<div>
<p><b>Performance:</b><br>
<?= ($overall>=100?'Excellent ⭐':($overall>=80?'Good 👍':($overall>=60?'Average ⚠️':'Poor ❌'))) ?>
</p>
</div>

</div>

<!-- OBJECTIVE -->
<div class="card">
<h2>🎯 Objective KPI</h2>
<?php foreach($objectiveScores as $v): ?>
<div class="item">
<b><?=$v[0]?> (<?=$v[1]?>/<?=$v[2]?>)</b>
<div class="progress">
<div class="bar" style="width:<?=($v[1]/$v[2])*100?>%;background:<?=$v[3]?>"></div>
</div>
</div>
<?php endforeach ?>
<b>Total: <?=$objectiveTotal?> / 50</b>
</div>

<!-- QUALITY -->
<div class="card">
<h2>⭐ Quality KPI</h2>
<?php foreach($qualityScores as $v): ?>
<div class="item">
<b><?=$v[0]?> (<?=$v[1]?>/<?=$v[2]?>)</b>
<div class="progress">
<div class="bar" style="width:<?=($v[1]/$v[2])*100?>%;background:<?=$v[3]?>"></div>
</div>
</div>
<?php endforeach ?>
<b>Total: <?=$qualityTotal?> / 25</b>
</div>

<!-- BEHAVIOR -->
<div class="card">
<h2>🧠 Behavior KPI</h2>
<?php foreach($behaviorScores as $v): ?>
<div class="item">
<b><?=$v[0]?> (<?=$v[1]?>/<?=$v[2]?>)</b>
<div class="progress">
<div class="bar" style="width:<?=($v[1]/$v[2])*100?>%;background:<?=$v[3]?>"></div>
</div>
</div>
<?php endforeach ?>
<b>Total: <?=$behaviorTotal?> / 25</b>
</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'}}
}
});
</script>
<script src="assets/particles.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
