<?php
require __DIR__ . '/../app/bootstrap.php';
require __DIR__ . '/../app/pages/_common.php';

auth_require();
require_perm('export_maintenance_pdf');

function col_exists(string $table, string $col): bool {
  $row = db_one(
    "SELECT COUNT(*) c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?",
    [$table,$col]
  );
  return intval($row['c'] ?? 0) > 0;
}
$has_category = col_exists('maintenance_requests','category');
$cat_select = $has_category ? "mr.category" : "''";

$sql = "SELECT mr.id, {$cat_select} AS category, mr.title, mr.priority, mr.status, mr.reported_at,
                a.tag AS asset_tag,
                ct.name AS contractor_name,
                c.contract_no
                FROM maintenance_requests mr
                JOIN assets a ON a.id=mr.asset_id
                LEFT JOIN contractors ct ON ct.id=mr.contractor_id
                LEFT JOIN contracts c ON c.id=mr.contract_id
                ORDER BY mr.reported_at DESC
                LIMIT 250";

$rows = db_all($sql);


$lines = [];
$lines[] = "Maintenance Report (latest 250)";
$lines[] = "Generated: " . date('Y-m-d H:i:s');
$lines[] = str_repeat('-', 140);
$lines[] = sprintf("%-6s | %-14s | %-8s | %-10s | %-22s | %-14s | %-16s | %-40s",
  "ID","ASSET","PRIOR","STATUS","CONTRACTOR","CONTRACT","REPORTED","TITLE"
);
$lines[] = str_repeat('-', 140);

foreach ($rows as $r) {
  $contractor = (string)($r['contractor_name'] ?? '');
  $contractor = substr($contractor, 0, 22);
  $contract_no = (string)($r['contract_no'] ?? '');
  $contract_no = substr($contract_no, 0, 14);
  $title = (string)($r['title'] ?? '');
  $title = substr($title, 0, 40);

  $lines[] = sprintf("%-6s | %-14s | %-8s | %-10s | %-22s | %-14s | %-16s | %-40s",
    $r['id'],
    $r['asset_tag'],
    $r['priority'],
    $r['status'],
    ($contractor!==''?$contractor:'-'),
    ($contract_no!==''?$contract_no:'-'),
    $r['reported_at'],
    $title
  );
}

$pdf = pdf_output_lines($lines, 'Maintenance Report');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="maintenance-report.pdf"');
echo $pdf;
exit;
