<?php
require_once(__DIR__ . '/../../config.php');
require_once(__DIR__ . '/../../libs/tcpdf/tcpdf.php');

/* ========================
   SEGURIDAD
======================== */
if (!$_settings->is_logged_in()) {
    exit('Acceso denegado');
}

/* ========================
   PARAMETROS
======================== */
$project_id = (int)($_GET['project_id'] ?? 0);
$period = $_GET['period'] ?? date('Y-m-01');

/* ========================
   PROYECTO
======================== */
$project = $conn->query("
    SELECT *
    FROM projects
    WHERE id = $project_id
")->fetch_assoc();

if(!$project){
    exit('Proyecto no encontrado');
}

/* ========================
   DETALLE ACTIVIDADES
======================== */
$qry = $conn->query("
    SELECT
        d.deliverable_name,
        a.activity_name,
        a.weight,
        IFNULL(m.planned,0) AS planned,
        IFNULL(m.executed,0) AS executed
    FROM project_deliverables d
    INNER JOIN project_activities_bn a ON a.deliverable_id = d.id
    LEFT JOIN project_activity_monthly m
        ON m.activity_id = a.id
       AND m.period = '$period'
    WHERE d.project_id = $project_id
    ORDER BY d.sort_order, a.sort_order
");

$rows = [];
$planificado = 0;
$ejecutado = 0;

while($r = $qry->fetch_assoc()){
    $rows[] = $r;
    $planificado += (float)$r['weight'];
    if($r['planned'] > 0){
        $ejecutado += $r['weight'] * min($r['executed'] / $r['planned'],1);
    }
}

$indice = ($planificado > 0) ? round($ejecutado / $planificado, 4) : 0;

if($indice >= 0.95){
    $semaforo = 'EN LÍNEA';
}elseif($indice >= 0.90){
    $semaforo = 'OBSERVACIÓN';
}else{
    $semaforo = 'RIESGO';
}

/* ========================
   PDF
======================== */
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica','',10);

/* TITULO */
$pdf->Cell(0,10,'FICHA DE AVANCE MENSUAL - PMO',0,1,'C');
$pdf->Ln(2);

$pdf->Cell(0,8,'Proyecto: '.$project['project_name'],0,1);
$pdf->Cell(0,8,'Periodo: '.date('F Y', strtotime($period)),0,1);
$pdf->Cell(0,8,'Líder PO: '.$project['leader_project'],0,1);
$pdf->Cell(0,8,'Estado PMO: '.$semaforo,0,1);

$pdf->Ln(4);

/* TABLA */
$html = '
<table border="1" cellpadding="4">
<tr bgcolor="#eeeeee">
<th><b>Entregable</b></th>
<th><b>Actividad</b></th>
<th><b>Peso</b></th>
<th><b>Plan %</b></th>
<th><b>Ejecutado %</b></th>
</tr>';

foreach($rows as $r){
    $html .= '
    <tr>
        <td>'.$r['deliverable_name'].'</td>
        <td>'.$r['activity_name'].'</td>
        <td>'.$r['weight'].'%</td>
        <td>'.$r['planned'].'%</td>
        <td>'.$r['executed'].'%</td>
    </tr>';
}

$html .= '</table>';

$pdf->writeHTML($html);

$pdf->Ln(4);
$pdf->Cell(0,8,'Índice BN: '.$indice,0,1);

$pdf->Output(
    'Ficha_Avance_'.$project['project_name'].'_'.date('Ym',strtotime($period)).'.pdf',
    'I'
);
