<?php

##################################################################################
# HOTELDRUID
# Copyright (C) 2001-2025 by Marco Maria Francesco De Santis (marco@digitaldruid.net)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version accepted by Marco Maria Francesco De Santis, which
# shall act as a proxy as defined in Section 14 of version 3 of the
# license.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
##################################################################################
#
# FICHERO NUEVO para la Residencia Julio Cienfuegos (2026), con la misma
# licencia. Lo incluye electricidad.php (pdf_lecturas=1): hoja de una cara
# A4 para anotar a mano las lecturas de los contadores: apartamento,
# última lectura guardada y casilla en blanco. La página se divide en dos
# columnas para que las casillas sean grandes. PDF escrito a mano (sin
# librerías), con las fuentes Helvetica estándar.
#
##################################################################################

if (!isset($mes) or !isset($apartamentos)) exit;

# Si el mes elegido ya tiene lecturas, la hoja es para el mes siguiente;
# si no, es para el mes elegido (con las lecturas del mes anterior)
$res = esegui_query("select count(*) as n from $tablelecturas where mes = '$mes'");
if ((int) risul_query($res,0,'n') > 0) {
$mes_lec = $mes;
$mes_hoja = date("Y-m",mktime(0,0,0,(int) substr($mes,5,2) + 1,1,(int) substr($mes,0,4)));
} # fine if ((int) risul_query($res,0,'n') > 0)
else {
$mes_lec = $mes_ant;
$mes_hoja = $mes;
} # fine else if ((int) risul_query($res,0,'n') > 0)
$ultima = array();
$res = esegui_query("select apartamento,lectura from $tablelecturas where mes = '$mes_lec'");
for ($num1 = 0 ; $num1 < numlin_query($res) ; $num1++) $ultima[risul_query($res,$num1,'apartamento')] = risul_query($res,$num1,'lectura');


# Utilidades del PDF
function pl_txt ($t) {
$t = (string) $t;
$c = function_exists("iconv") ? @iconv("UTF-8","CP1252//TRANSLIT",$t) : false;
if ($c === false) $c = mb_convert_encoding($t,"CP1252","UTF-8");
return str_replace(array("\\","(",")"),array("\\\\","\\(","\\)"),$c);
} # fine function pl_txt
# Ancho aproximado en puntos (Helvetica; cifras exactas)
function pl_ancho ($t,$tam,$negrita = 0) {
$w = 0;
$anchos = array('0' => 556,'1' => 556,'2' => 556,'3' => 556,'4' => 556,'5' => 556,'6' => 556,'7' => 556,'8' => 556,'9' => 556,',' => 278,'.' => 278,' ' => 278,'-' => 333,'/' => 278,'i' => 222,'l' => 222,'t' => 278,'f' => 278,'r' => 333);
foreach (preg_split('//u',(string) $t,-1,PREG_SPLIT_NO_EMPTY) as $ch) $w += isset($anchos[$ch]) ? $anchos[$ch] : 556;
return $w * $tam / 1000 * ($negrita ? 1.05 : 1);
} # fine function pl_ancho
$pl = "";
# texto: x,y desde abajo a la izquierda; alin: i (izquierda), d (derecha), c (centro)
function pl_t ($x,$y,$t,$tam = 9,$negrita = 0,$alin = "i") {
global $pl;
if ($alin == "d") $x -= pl_ancho($t,$tam,$negrita);
if ($alin == "c") $x -= pl_ancho($t,$tam,$negrita) / 2;
$pl .= "BT /".($negrita ? "F2" : "F1")." $tam Tf ".round($x,2)." ".round($y,2)." Td (".pl_txt($t).") Tj ET\n";
} # fine function pl_t
function pl_linea ($x1,$y1,$x2,$y2,$grosor = 0.5,$gris = 0) {
global $pl;
$pl .= "$gris G $grosor w ".round($x1,2)." ".round($y1,2)." m ".round($x2,2)." ".round($y2,2)." l S 0 G\n";
} # fine function pl_linea
function pl_caja ($x,$y,$w,$h,$gris) {
global $pl;
$pl .= "$gris g ".round($x,2)." ".round($y,2)." ".round($w,2)." ".round($h,2)." re f 0 g\n";
} # fine function pl_caja


# Página A4 (595 x 842 pt), dos columnas
$izq = 22;
$der = 573;
$y = 812;
pl_t($izq,$y,"Lecturas de contadores de luz: fin de ".el_nombre_mes($mes_hoja),15,1);
pl_t($der,$y,"Residencia Julio Cienfuegos",8,0,"d");
$y -= 15;
pl_t($izq,$y,"Fecha de la lectura: ____________ Anotado por: ______________________",9);
pl_t($der,$y,"Impreso el ".date("d-m-Y"),7,0,"d");
$y -= 10;

$lista = array_keys($apartamentos);
$n = count($lista);
$filas = (int) ceil($n / 2);
$sep = 14;
$w_col = ($der - $izq - $sep) / 2;
$w_apto = 46;
$w_ant = 78;
$alto_cab = 22;
$alto = min(40,($y - 20 - $alto_cab) / max(1,$filas));
$y_tabla = $y;
$tam_apto = min(16,$alto * 0.55);
$tam_ant = min(12,$alto * 0.42);

for ($c = 0 ; $c < 2 ; $c++) {
$x0 = $izq + $c * ($w_col + $sep);
$x1 = $x0 + $w_apto;
$x2 = $x1 + $w_ant;
$x3 = $x0 + $w_col;
$yy = $y_tabla;
pl_caja($x0,$yy - $alto_cab,$w_col,$alto_cab,0.85);
pl_t($x0 + $w_apto / 2,$yy - 14,"Apto.",8.5,1,"c");
pl_t(($x1 + $x2) / 2,$yy - 9.5,"Lectura fin de",7.5,1,"c");
pl_t(($x1 + $x2) / 2,$yy - 18.5,el_nombre_mes($mes_lec),7.5,1,"c");
pl_t(($x2 + $x3) / 2,$yy - 9.5,"Lectura fin de",7.5,1,"c");
pl_t(($x2 + $x3) / 2,$yy - 18.5,el_nombre_mes($mes_hoja),7.5,1,"c");
$yy -= $alto_cab;
$filas_col = 0;
for ($i = $c * $filas ; $i < min($n,($c + 1) * $filas) ; $i++) {
$apto = $lista[$i];
if ($filas_col % 2 == 1) pl_caja($x0,$yy - $alto,$x2 - $x0,$alto,0.94);
pl_t($x0 + $w_apto / 2,$yy - $alto / 2 - $tam_apto * 0.35,$apto,$tam_apto,1,"c");
$ant = isset($ultima[$apto]) ? el_ver_num($ultima[$apto]) : "";
if ($ant !== "") pl_t($x2 - 6,$yy - $alto / 2 - $tam_ant * 0.35,$ant,$tam_ant,0,"d");
$yy -= $alto;
pl_linea($x0,$yy,$x3,$yy,0.5,0.35);
$filas_col++;
} # fine for $i
# Marco y líneas verticales
$y_fin = $yy;
pl_linea($x0,$y_tabla,$x3,$y_tabla,0.9);
pl_linea($x0,$y_fin,$x3,$y_fin,0.9);
pl_linea($x0,$y_tabla - $alto_cab,$x3,$y_tabla - $alto_cab,0.9);
pl_linea($x0,$y_tabla,$x0,$y_fin,0.9);
pl_linea($x1,$y_tabla,$x1,$y_fin,0.5,0.35);
pl_linea($x2,$y_tabla,$x2,$y_fin,0.9);
pl_linea($x3,$y_tabla,$x3,$y_fin,0.9);
} # fine for $c


# Montar el PDF
$fuente = function ($nombre) { return "<< /Type /Font /Subtype /Type1 /BaseFont /$nombre /Encoding /WinAnsiEncoding >>"; };
$obj = array(
1 => "<< /Type /Catalog /Pages 2 0 R >>",
2 => "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
3 => "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R /F2 5 0 R >> >> /Contents 6 0 R >>",
4 => $fuente("Helvetica"),
5 => $fuente("Helvetica-Bold"),
6 => "<< /Length ".strlen($pl)." >>\nstream\n".$pl."endstream",
7 => "<< /Title (".pl_txt("Lecturas ".el_nombre_mes($mes_hoja)).") /Producer (HotelDruid - Residencia) >>",
);
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
$pos = array();
foreach ($obj as $i => $o) {
$pos[$i] = strlen($pdf);
$pdf .= "$i 0 obj\n$o\nendobj\n";
} # fine foreach $obj
$xref = strlen($pdf);
$pdf .= "xref\n0 ".(count($obj) + 1)."\n0000000000 65535 f \n";
foreach ($pos as $p) $pdf .= sprintf("%010d 00000 n \n",$p);
$pdf .= "trailer\n<< /Size ".(count($obj) + 1)." /Root 1 0 R /Info 7 0 R >>\nstartxref\n$xref\n%%EOF\n";

header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=\"Lecturas_".$mes_hoja.".pdf\"");
header("Content-Length: ".strlen($pdf));
header("Cache-Control: no-store");
echo $pdf;

?>