<?php
require_once('./../config.php');

if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    echo json_encode(['status'=>'error','msg'=>'Método no permitido']);
    exit;
}

$project_id = $_POST['project_id'] ?? null;
$period = $_POST['period'] ?? null;
$p = isset($_POST['planned_progress']) ? (int)$_POST['planned_progress'] : 0;
$r = isset($_POST['real_progress']) ? (int)$_POST['real_progress'] : 0;
$comment = $_POST['comment'] ?? '';

// ===============================
// CÁLCULO DE SEMÁFORO (OFICIAL)
// ===============================
// 🟢 ≥ 95 %
// 🟡 < 95 % y > 90 %
// 🔴 ≤ 90 %
// ⚪ Sin color → no hay entregables planificados
if($p === 0){
    $traffic_light = null; // Sin reporte
}else{
    $cumplimiento = ($r / $p) * 100;

    if($cumplimiento >= 95){
        $traffic_light = 'green';
    }elseif($cumplimiento > 90){
        $traffic_light = 'amber';
    }else{
        $traffic_light = 'red';
    }
}

// ===============================
// GUARDAR / ACTUALIZAR SEGUIMIENTO
// ===============================
$sql = "
INSERT INTO project_followups
(project_id, period, planned_progress, real_progress, comment, traffic_light)
VALUES (?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE
    planned_progress = VALUES(planned_progress),
    real_progress    = VALUES(real_progress),
    comment          = VALUES(comment),
    traffic_light    = VALUES(traffic_light)
";

$stmt = $conn->prepare($sql);

if(!$stmt){
    echo json_encode(['status'=>'error','msg'=>$conn->error]);
    exit;
}

$stmt->bind_param(
    "isiiss",
    $project_id,
    $period,
    $p,
    $r,
    $comment,
    $traffic_light
);

if($stmt->execute()){
    echo json_encode(['status'=>'success']);
}else{
    echo json_encode(['status'=>'error','msg'=>$stmt->error]);
}
