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

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

if(isset($_POST['save_target'])){
    $stmt = $pdo->prepare("
        INSERT INTO sales_targets (month, year, target_amount)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE target_amount = VALUES(target_amount)
    ");
    $stmt->execute([
        $_POST['month'],
        $_POST['year'],
        $_POST['target_amount']
    ]);
    header("Location: set_target.php?month=".$_POST['month']."&year=".$_POST['year']);
    exit;
}

$tq = $pdo->prepare("SELECT target_amount FROM sales_targets WHERE month=? AND year=?");
$tq->execute([$month,$year]);
$targetAmount = $tq->fetchColumn() ?? 0;

$aq = $pdo->prepare("
    SELECT SUM(payment_received)
    FROM projects
    WHERE MONTH(created_at)=? AND YEAR(created_at)=?
");
$aq->execute([$month,$year]);
$achievedAmount = $aq->fetchColumn() ?? 0;

$remaining  = max(0, $targetAmount - $achievedAmount);
$status     = ($achievedAmount >= $targetAmount && $targetAmount > 0) ? 'ACHIEVED' : 'IN PROGRESS';
$percentage = ($targetAmount > 0) ? round(($achievedAmount/$targetAmount)*100,1) : 0;

// Employee contributions
$contributionQ = $pdo->prepare("
    SELECT s.full_name, SUM(p.payment_received) amount
    FROM projects p
    JOIN sales_employees s ON s.id = p.sales_id
    WHERE MONTH(p.created_at)=? AND YEAR(p.created_at)=?
    GROUP BY p.sales_id
    ORDER BY amount DESC
");
$contributionQ->execute([$month,$year]);

$names=[]; 
$amounts=[];

while($r=$contributionQ->fetch()){
    $names[]   = $r['full_name'];
    $amounts[] = (float)$r['amount'];
}

$totalEmployees = count($names);
$employeeTarget = ($totalEmployees>0)?round($targetAmount/$totalEmployees,2):0;

$empAchieved = $amounts;
$empPercentAchieved = [];
$empRemaining = [];
$empPercentContribution = [];

foreach($empAchieved as $amt){
    $empPercentAchieved[] = ($employeeTarget>0)?round(($amt/$employeeTarget)*100,1):0;
    $empRemaining[] = max(0, $employeeTarget - $amt);
    $empPercentContribution[] = ($targetAmount>0)?round(($amt/$targetAmount)*100,1):0;
}
include 'assets/layout_top.php';
?>

<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/png" href="images/jg.webp">
<title>JG - Suite</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
<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:1300px;
    margin:auto;
    padding:30px;
}
.header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:15px;
}
.header h1{font-size:26px; color:#fff;}
.header form{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}
.header select,
.header input,
.header button{
    padding:8px 12px;
    border-radius:8px;
    border:1px solid #333;
    background:#151a2e;
    color:#fff;
}
.header button{
    background:#1f8cff;
    color:#fff;
    border:none;
    cursor:pointer;
}

.grid1{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(240px,1fr));
    gap:20px;
    margin-top:25px;
}

.card{
    background:rgba(255,255,255,0.05);
    backdrop-filter:blur(10px);
    padding:22px;
    border-radius:16px;
    box-shadow:0 8px 24px rgba(0,0,0,0.3);
    border:1px solid rgba(255,255,255,0.1);
    color:#fff;
}

.kpi{
    display:flex;
    justify-content:space-between;
    align-items:center;
}
.kpi h3{font-size:14px;color:#aaa}
.kpi h2{margin:0;font-size:26px}

.badge{
    padding:20px;
    border-radius:999px;
    font-size:13px;
    font-weight:600;

}
.success{background:#22c55e;color:#0f172a}
.progress{background:#facc15;color:#0f172a}

.section{
    margin-top:30px;
}

table{
    width:100%;
    border-collapse:collapse;
    margin-top:15px;
    color:#fff;
}
th,td{
    padding:12px;
    border-bottom:1px solid rgba(255,255,255,0.1);
}
th{color:#aaa;font-size:13px;text-transform:uppercase}
tr:nth-child(even){background:rgba(255,255,255,0.05);}
tr:hover{background:rgba(31,140,255,0.1);}

</style>
</head>

<body>
<br><br>
<div class="container">

<div class="header">
    <h1>📊 Sales Target Dashboard</h1>

    <!-- VIEW MONTH/YEAR -->
    <form method="get">
        <select name="month">
            <?php for($m=1;$m<=12;$m++){ ?>
            <option value="<?=$m?>" <?=$m==$month?'selected':''?>><?=$m?></option>
            <?php } ?>
        </select>

        <input type="number" name="year" value="<?=$year?>" style="width:90px">
        <button type="submit">View</button>
    </form>

    <!-- SAVE TARGET -->
    <form method="post">
        <select name="month">
<?php for($m=1;$m<=12;$m++){ ?>
<option value="<?=$m?>" <?=$m==$month?'selected':''?>><?=$m?></option>
<?php } ?>
</select>
<input type="number" name="year" value="<?=$year?>" style="width:90px">
<input type="number" name="target_amount" placeholder="Target Amount" required>
<button name="save_target">Save</button>
</form>
</div>

<!-- KPI -->
<div class="grid1">
<div class="card kpi">
<div>
<h3>Total Target</h3>
<h2>$ <?=number_format($targetAmount)?></h2>
</div>
</div>

<div class="card kpi">
<div>
<h3>Achieved</h3>
<h2>$ <?=number_format($achievedAmount)?></h2>
</div>
</div>

<div class="card kpi">
<div>
<h3>Remaining</h3>
<h2>$ <?=number_format($remaining)?></h2>
</div>
</div>

<div class="card kpi">
<div>
<h3>Status</h3>
<span class="badge <?=$status=='ACHIEVED'?'success':'progress'?>">
<?=$status?> • <?=$percentage?>%
</span>
</div>
</div>
</div>

<!-- Charts & Table -->
<div class="section card">
<h3>Chart</h3>
<canvas id="empChart" height="130"></canvas>

<table>
<tr>
    <th>Rank</th>
    <th>Employee</th>
    <th>Contribution ($)</th>
    <th>% of Team Target</th>
    <th>Employee Target ($)</th>
    <th>Achieved ($)</th>
    <th>% Achieved</th>
    <th>Remaining ($)</th>
</tr>

<?php foreach($names as $i=>$n){ ?>
<tr>
    <td>
        <?php 
            if($i==0) echo "🥇";
            elseif($i==1) echo "🥈";
            elseif($i==2) echo "🥉";
            else echo $i+1;
        ?>
    </td>
    <td><?=$n?></td>
    <td>$ <?=number_format($amounts[$i],2)?></td>
    <td><?=$empPercentContribution[$i]?>%</td>
    <td>$ <?=number_format($employeeTarget,2)?></td>
    <td>$ <?=number_format($empAchieved[$i],2)?></td>
    <td><?=$empPercentAchieved[$i]?>%</td>
    <td>$ <?=number_format($empRemaining[$i],2)?></td>
</tr>
<?php } ?>
</table>
</div>

</div>

<script>
const labels = [...<?=json_encode($names)?>,'Total Achieved','Monthly Target'];
const dataValues = [...<?=json_encode($amounts)?>, <?=$achievedAmount?>, <?=$targetAmount?>];
const colors = [...Array(<?=count($names)?>).fill('#1f8cff'),'#22c55e','#3b82f6'];

new Chart(empChart,{
    type:'bar',
    data:{
        labels: labels,
        datasets:[{
            label:'Monthly Performance',
            data: dataValues,
            backgroundColor: colors,
            borderRadius:10
        }]
    },
    options:{
        responsive:true,
        scales:{
            y:{beginAtZero:true}
        },
        plugins:{
            legend:{display:false},
            tooltip:{
                callbacks:{
                    label:function(ctx){ return '$ ' + ctx.raw.toLocaleString(); }
                }
            }
        }
    }
});
</script>

</body>
</html>
<?php
/* ===== LAYOUT END ===== */
include 'assets/layout_bottom.php';
?>