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

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

// Save Individual Target
if(isset($_POST['save_target'])){
    $emp_id_post = $_POST['emp_id'];
    $month_post  = $_POST['month'];
    $year_post   = $_POST['year'];
    $target_post = $_POST['target_amount'];

    // check if target already exists
    $check = $pdo->prepare("SELECT id FROM employee_targets WHERE emp_id=? AND month=? AND year=?");
    $check->execute([$emp_id_post,$month_post,$year_post]);
    if($check->rowCount() == 0){
        $stmt = $pdo->prepare("INSERT INTO employee_targets (emp_id, month, year, target_amount) VALUES (?,?,?,?)");
        $stmt->execute([$emp_id_post,$month_post,$year_post,$target_post]);
    }

    // UPDATE KPI
    $aq = $pdo->prepare("SELECT SUM(payment_received) FROM projects WHERE sales_id=? AND MONTH(created_at)=? AND YEAR(created_at)=?");
    $aq->execute([$emp_id_post, $month_post, $year_post]);
    $achieved = (float)$aq->fetchColumn() ?? 0;
    $percent_individual = ($target_post > 0) ? round(($achieved/$target_post)*100,1) : 0;

    $upsert = $pdo->prepare("
        INSERT INTO sales_objective_kpi 
        (sales_id, full_name, month, year, percent_individual_target)
        SELECT id, full_name, ?, ?, ? FROM sales_employees WHERE id=?
        ON DUPLICATE KEY UPDATE 
        percent_individual_target=VALUES(percent_individual_target),
        updated_at=CURRENT_TIMESTAMP
    ");
    $upsert->execute([$month_post,$year_post,$percent_individual,$emp_id_post]);

    header("Location: employee_targets.php?emp_id=$emp_id_post&month=$month_post&year=$year_post");
    exit;
}

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

// GET TARGET & ACHIEVED
$targetAmount = 0;
$achievedAmount = 0;

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

    $aq = $pdo->prepare("SELECT SUM(payment_received) FROM projects WHERE sales_id=? AND MONTH(created_at)=? AND YEAR(created_at)=?");
    $aq->execute([$emp_id,$month,$year]);
    $achievedAmount = (float)$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;

    // Update KPI
    $upsert = $pdo->prepare("
        INSERT INTO sales_objective_kpi 
        (sales_id, full_name, month, year, percent_individual_target)
        SELECT id, full_name, ?, ?, ? FROM sales_employees WHERE id=?
        ON DUPLICATE KEY UPDATE 
        percent_individual_target=VALUES(percent_individual_target),
        updated_at=CURRENT_TIMESTAMP
    ");
    $upsert->execute([$month,$year,$percentage,$emp_id]);
}

/* ===== PAGE TITLE ===== */
$page_title = "Individual Employee Target";

/* ===== LAYOUT START ===== */
include 'assets/layout_top.php';
?>

<div class="glass-panel">

<h3 class="mb-4 text-center">📊 Individual Employee Target</h3>

<!-- FILTER / VIEW -->
<form method="get" class="d-flex gap-2 flex-wrap mb-4 justify-content-center">
<select name="emp_id" class="form-select w-auto" required>
<option value="">Select Employee</option>
<?php foreach($emps as $e){ ?>
<option value="<?=$e['id']?>" <?=($emp_id==$e['id']?'selected':'')?>><?=$e['full_name']?></option>
<?php } ?>
</select>

<select name="month" class="form-select w-auto">
<?php for($m=1;$m<=12;$m++){ ?>
<option value="<?=$m?>" <?=$m==$month?'selected':''?>><?=$m?></option>
<?php } ?>
</select>

<input type="number" name="year" value="<?=$year?>" class="form-control w-auto" placeholder="Year">
<button type="submit" class="btn-main">View</button>
</form>

<!-- SAVE TARGET -->
<form method="post" class="d-flex gap-2 flex-wrap mb-4 justify-content-center">
<select name="emp_id" class="form-select w-auto" required>
<option value="">Select Employee</option>
<?php foreach($emps as $e){ ?>
<option value="<?=$e['id']?>"><?=$e['full_name']?></option>
<?php } ?>
</select>

<select name="month" class="form-select w-auto">
<?php for($m=1;$m<=12;$m++){ ?>
<option value="<?=$m?>" <?=$m==$month?'selected':''?>><?=$m?></option>
<?php } ?>
</select>

<input type="number" name="year" value="<?=$year?>" class="form-control w-auto" placeholder="Year">
<input type="number" name="target_amount" placeholder="Target Amount" class="form-control w-auto" required>
<button name="save_target" class="btn-main">Save Target</button>
</form>

<?php if($emp_id): ?>
<!-- KPI -->
<div class="d-flex flex-wrap gap-3 justify-content-center mb-4">
<div class="glass-card text-center p-3" style="min-width:180px">
<h6>Total Target</h6>
<h4>$ <?=number_format($targetAmount)?></h4>
</div>
<div class="glass-card text-center p-3" style="min-width:180px">
<h6>Achieved</h6>
<h4>$ <?=number_format($achievedAmount)?></h4>
</div>
<div class="glass-card text-center p-3" style="min-width:180px">
<h6>Remaining</h6>
<h4>$ <?=number_format($remaining)?></h4>
</div>
<div class="glass-card text-center p-3" style="min-width:180px">
<h6>Status</h6>
<span style="color:black;" class="badge <?=($status=='ACHIEVED'?'success':'progress')?>"><?=$status?> • <?=$percentage?>%</span>
</div>
</div>

<!-- PERFORMANCE CHART -->
<div class="glass-card p-3">
<h5>🎯 Performance Chart</h5>
<canvas id="empChart" height="130"></canvas>
</div>

<script>
const labels = ['Target','Achieved'];
const dataValues = [<?=$targetAmount?>,<?=$achievedAmount?>];
const colors = ['#3b82f6','#22c55e'];

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:{position:'top'},
                 tooltip:{
                     callbacks:{
                         label:function(ctx){ return 'Rs '+ctx.raw.toLocaleString(); }
                     }
                 }}
    }
});
</script>
<?php endif; ?>

</div>

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