<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

ob_start();

$_POST['per2'] = '9';
$_POST['cur2'] = '12';
$_POST['estudiante2'] = '160008';

include '../conector.php';
include 'fpdf.php';

class PDF extends FPDF
{
    function Header() {
        global $_POST;
        
        $sel_estudiante="select nombre from estudiante where estudiante_id=".$_POST['estudiante2']." ";
        $res = mysql_query($sel_estudiante);
        $est = mysql_fetch_array($res);
        
        $sel_curso="select codigo,nombre from curso where curso_id=".$_POST['cur2']." ";
        $res2 = mysql_query($sel_curso);
        $curso = mysql_fetch_array($res2);
        
        $sel_planilla="select anno,periodo from planilla where id=".$_POST['per2']." ";
        $res3 = mysql_query($sel_planilla);
        $planilla = mysql_fetch_array($res3);
        
        $this->SetFont('Arial','B',14);
        $this->Cell(0,8,'INFORME FINAL - ' . $est[0],0,1,'C');
        $this->SetFont('Arial','',10);
        $this->Cell(0,5,'Curso: ' . $curso[0] . ' ' . $curso[1] . ' | Periodo: ' . $planilla[1] . ' | Año: ' . $planilla[0],0,1,'C');
        $this->Ln(5);
        
        $this->SetFont('Arial','B',9);
        $this->Cell(6,0.5,'Materia',1,0,'C');
        $this->Cell(2,0.5,'Nota',1,0,'C');
        $this->Cell(8,0.5,'Actividad/Concepto',1,1,'C');
    }
}

$pdf = new PDF('P','cm','letter');
$pdf->AddPage();

// Query usando planilla_detalle directamente
$query = "SELECT p.nombre as materia, pd.nota, pd.concepto, pd.comp_1, pd.comp_2, pd.comp_3
FROM planilla_detalle pd
JOIN pensum p ON pd.codigo_pensum = p.subject_id
JOIN estudiante e ON pd.codigo_est = e.estudiante_id
WHERE pd.planilla = ".$_POST['per2']." 
AND e.estudiante_id = ".$_POST['estudiante2']."
AND p.class_id = ".$_POST['cur2']."
AND p.estado = 'A'
ORDER BY p.nombre, pd.fecha_insert";

$res = mysql_query($query);
$num = mysql_num_rows($res);
echo "Resultados: $num\n";

if($num > 0){
    $materia_actual = '';
    while($row = mysql_fetch_assoc($res)){
        if($row['materia'] != $materia_actual){
            $materia_actual = $row['materia'];
            $pdf->SetFont('Arial','B',8);
            $pdf->Cell(6,0.4,$row['materia'],1,0,'L');
        } else {
            $pdf->SetFont('Arial','',8);
            $pdf->Cell(6,0.4,'',1,0,'L');
        }
        
        $nota = $row['nota'] > 0 ? $row['nota'] : '-';
        $pdf->Cell(2,0.4,$nota,1,0,'C');
        $pdf->Cell(8,0.4,substr($row['concepto'],0,50),1,1,'L');
    }
} else {
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(0,10,'No hay datos para este estudiante en este periodo',0,1);
}

$output = $pdf->Output('', 'S');
ob_end_clean();

header('Content-Type: application/pdf');
echo $output;
?>