<?php
// api/generate_pdf.php — Genera PDF de propuestas de diseño
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
dm_require_login();

$id = (int)($_GET['id'] ?? 0);
if (!$id) { http_response_code(400); echo 'ID requerido'; exit; }

$stmt = $pdo->prepare("SELECT * FROM dm_proposals WHERE id=?");
$stmt->execute([$id]);
$p = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$p) { http_response_code(404); echo 'Propuesta no encontrada'; exit; }

if (empty($p['proposal_1']) && empty($p['proposal_2']) && empty($p['proposal_3']) && empty($p['proposal_final'])) {
    http_response_code(400); echo 'No hay propuestas generadas aún'; exit;
}

// Detectar binarios en múltiples ubicaciones comunes en cPanel/Linux
function find_bin(string $name): string {
    $result = trim((string)@shell_exec('which ' . escapeshellarg($name) . ' 2>/dev/null'));
    if ($result && file_exists($result)) return $result;
    $candidates = [
        "/usr/local/bin/{$name}",
        "/usr/bin/{$name}",
        "/bin/{$name}",
        "/opt/cpanel/ea-php74/root/usr/bin/{$name}",
        "/home/" . get_current_user() . "/bin/{$name}",
    ];
    foreach ($candidates as $c) {
        if (file_exists($c) && is_executable($c)) return $c;
    }
    return '';
}

// Wrapper que intenta exec → shell_exec → system si alguno está deshabilitado
function run_cmd(string $cmd): void {
    if (function_exists('exec'))       { @exec($cmd); return; }
    if (function_exists('shell_exec')) { @shell_exec($cmd); return; }
    if (function_exists('system'))     { ob_start(); @system($cmd); ob_end_clean(); return; }
    if (function_exists('passthru'))   { ob_start(); @passthru($cmd); ob_end_clean(); return; }
}

$wkhtmltopdf_bin = find_bin('wkhtmltopdf');
if (!$wkhtmltopdf_bin) {
    // Fallback: página HTML para imprimir como PDF desde el navegador
    $pn = htmlspecialchars($p['project_name'], ENT_QUOTES, 'UTF-8');
    $pages = [];
    foreach ([1,2,3] as $n) {
        if (!empty($p["proposal_{$n}"])) {
            $nm = htmlspecialchars($p["proposal_{$n}_name"] ?: "Propuesta {$n}", ENT_QUOTES, 'UTF-8');
            $pages[] = ['title'=>$nm, 'num'=>$n, 'html'=>$p["proposal_{$n}"]];
        }
    }
    if (!empty($p['proposal_final'])) {
        $nm = htmlspecialchars($p['proposal_final_name'] ?: 'Versión Final', ENT_QUOTES, 'UTF-8');
        $pages[] = ['title'=>$nm, 'num'=>'F', 'html'=>$p['proposal_final']];
    }
    header('Content-Type: text/html; charset=UTF-8');
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Propuestas ' . $pn . '</title><style>
    *{box-sizing:border-box;margin:0;padding:0}
    body{font-family:Arial,sans-serif;background:#111;color:#fff}
    .toolbar{position:fixed;top:0;left:0;right:0;background:#1a1a1a;border-bottom:1px solid #333;padding:12px 20px;display:flex;align-items:center;justify-content:space-between;z-index:999;gap:12px}
    .toolbar h1{font-size:14px;font-weight:600}
    .toolbar button{padding:8px 20px;background:#E8272A;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;font-weight:600}
    .spacer{height:56px}
    .sep-page{background:#0f0f0f;display:flex;align-items:center;justify-content:center;min-height:100vh;flex-direction:column;text-align:center;gap:12px}
    .sep-num{font-size:100px;font-weight:900;opacity:.08;line-height:1}
    .sep-label{font-size:11px;letter-spacing:3px;text-transform:uppercase;opacity:.4}
    .sep-name{font-size:36px;font-weight:800}
    .sep-line{width:60px;height:4px;background:#E8272A;margin:0 auto}
    .prop-wrap{width:100%;overflow:hidden}
    .prop-wrap iframe{width:1440px;height:900px;border:none;transform:scale(0.7);transform-origin:top left;display:block}
    @media print{
      .toolbar,.spacer{display:none}
      .sep-page{page-break-after:always;break-after:page;background:#0f0f0f;color:#fff;-webkit-print-color-adjust:exact;print-color-adjust:exact}
      .prop-wrap{page-break-after:always;break-after:page}
      .prop-wrap iframe{transform:none;width:100%;height:auto}
    }
    </style></head><body>';
    echo '<div class="toolbar"><h1>📄 Propuestas — ' . $pn . '</h1><button onclick="window.print()">Guardar como PDF (Ctrl+P)</button></div><div class="spacer"></div>';
    foreach ($pages as $pg) {
        echo '<div class="sep-page"><div class="sep-num">' . $pg['num'] . '</div><div class="sep-label">Propuesta</div><div class="sep-name">' . $pg['title'] . '</div><div class="sep-line"></div></div>';
        $blob = base64_encode($pg['html']);
        echo '<div class="prop-wrap"><iframe src="data:text/html;base64,' . $blob . '"></iframe></div>';
    }
    echo '<script>window.onload=function(){window.print()};</script></body></html>';
    exit;
}

$qpdf_bin = find_bin('qpdf');

$project           = preg_replace('/[^a-zA-Z0-9_-]/', '_', $p['project_name']);
$project_name_safe = htmlspecialchars($p['project_name'], ENT_QUOTES, 'UTF-8');
$date_fmt          = date('d/m/Y');
$tmp_dir           = sys_get_temp_dir() . '/proposal_' . $id . '_' . time();
mkdir($tmp_dir, 0755, true);

register_shutdown_function(function() use ($tmp_dir) {
    if (is_dir($tmp_dir)) {
        foreach (glob($tmp_dir . '/*') as $f) @unlink($f);
        @rmdir($tmp_dir);
    }
});

// Portada del PDF
$cover_html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: 'Arial', sans-serif; background:#0f0f0f; color:#fff; height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; }
.logo { font-size:48px; font-weight:900; color:#E8272A; letter-spacing:-2px; margin-bottom:8px; }
.logo span { color:#fff; }
.tagline { font-size:13px; letter-spacing:3px; text-transform:uppercase; color:rgba(255,255,255,.4); margin-bottom:60px; }
.divider { width:60px; height:3px; background:#E8272A; margin:0 auto 40px; }
.title { font-size:36px; font-weight:700; margin-bottom:12px; line-height:1.2; }
.subtitle { font-size:16px; color:rgba(255,255,255,.5); margin-bottom:60px; }
.meta { font-size:12px; color:rgba(255,255,255,.3); letter-spacing:1px; }
.badge { display:inline-block; background:#E8272A; color:#fff; font-size:11px; padding:4px 12px; border-radius:20px; margin-bottom:16px; letter-spacing:1px; text-transform:uppercase; }
</style>
</head>
<body>
<div class="badge">Propuesta de Diseño Web</div>
<div class="logo">D<span>IMARK</span></div>
<div class="tagline">Super Cerebro · Agencia Digital</div>
<div class="divider"></div>
<div class="title">{$project_name_safe}</div>
<div class="subtitle">Propuestas de diseño · Homepage</div>
<div class="meta">{$date_fmt} · Confidencial · Solo para el cliente</div>
</body>
</html>
HTML;

file_put_contents($tmp_dir . '/cover.html', $cover_html);

$styles = [
    1 => ['name' => $p['proposal_1_name'] ?: 'Moderno Bold',        'color' => '#1a1a2e', 'accent' => '#E8272A'],
    2 => ['name' => $p['proposal_2_name'] ?: 'Elegante Profesional', 'color' => '#f8f6f3', 'accent' => '#333'],
    3 => ['name' => $p['proposal_3_name'] ?: 'Fresco Dinámico',      'color' => '#0ea5e9', 'accent' => '#fff'],
];

$pdf_files  = [];
$base_opts  = "--quiet --page-size A4 --orientation Portrait --margin-top 0 --margin-bottom 0 --margin-left 0 --margin-right 0 --disable-smart-shrinking";
$land_opts  = "--quiet --page-size A4 --orientation Landscape --margin-top 5 --margin-bottom 5 --margin-left 5 --margin-right 5 --javascript-delay 1500 --no-stop-slow-scripts --disable-smart-shrinking";

// 1. Portada
$cover_pdf = $tmp_dir . '/00_cover.pdf';
$cmd = escapeshellarg($wkhtmltopdf_bin) . " {$base_opts} " . escapeshellarg($tmp_dir . '/cover.html') . " " . escapeshellarg($cover_pdf) . " 2>/dev/null";
run_cmd($cmd);
if (file_exists($cover_pdf) && filesize($cover_pdf) > 100) $pdf_files[] = $cover_pdf;

// 2. Propuestas 1, 2, 3
foreach ([1, 2, 3] as $n) {
    $html = $p["proposal_{$n}"] ?? '';
    if (empty($html)) continue;

    $s = $styles[$n];
    $is_dark   = (hexdec(substr(ltrim($s['color'],'#'),0,2)) < 128);
    $text_color = $is_dark ? '#ffffff' : '#1a1a1a';

    $sep_html = <<<SEPHTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:Arial,sans-serif; background:{$s['color']}; color:{$text_color}; height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; }
.num { font-size:120px; font-weight:900; opacity:.1; line-height:1; margin-bottom:-20px; }
.label { font-size:11px; letter-spacing:3px; text-transform:uppercase; opacity:.5; margin-bottom:8px; }
.name { font-size:42px; font-weight:800; letter-spacing:-1px; }
.accent-line { width:60px; height:4px; background:{$s['accent']}; margin:20px auto; opacity:.8; }
.desc { font-size:14px; opacity:.5; max-width:400px; line-height:1.6; }
</style>
</head>
<body>
<div class="num">{$n}</div>
<div class="label">Propuesta</div>
<div class="name">{$s['name']}</div>
<div class="accent-line"></div>
<div class="desc">Diseño de homepage para {$project_name_safe}</div>
</body>
</html>
SEPHTML;

    $sep_file = $tmp_dir . "/0{$n}_sep.html";
    $sep_pdf  = $tmp_dir . "/0{$n}_sep.pdf";
    file_put_contents($sep_file, $sep_html);
    $cmd = escapeshellarg($wkhtmltopdf_bin) . " {$base_opts} " . escapeshellarg($sep_file) . " " . escapeshellarg($sep_pdf) . " 2>/dev/null";
    run_cmd($cmd);
    if (file_exists($sep_pdf) && filesize($sep_pdf) > 100) $pdf_files[] = $sep_pdf;

    // Propuesta completa en landscape para ver mejor el diseño
    $prop_file = $tmp_dir . "/0{$n}_prop.html";
    $prop_pdf  = $tmp_dir . "/0{$n}_prop.pdf";
    $html_mod = str_replace(
        '</head>',
        '<style>html,body{zoom:0.65;-webkit-text-size-adjust:none}body{overflow:hidden}</style></head>',
        $html
    );
    file_put_contents($prop_file, $html_mod);
    $cmd = escapeshellarg($wkhtmltopdf_bin) . " {$land_opts} " . escapeshellarg($prop_file) . " " . escapeshellarg($prop_pdf) . " 2>/dev/null";
    run_cmd($cmd);
    if (file_exists($prop_pdf) && filesize($prop_pdf) > 100) $pdf_files[] = $prop_pdf;
}

// 3. Versión final (si existe)
$has_final = !empty($p['proposal_final']);
if ($has_final) {
    $final_name_safe = htmlspecialchars($p['proposal_final_name'] ?: 'Versión Final', ENT_QUOTES, 'UTF-8');

    $final_sep_html = <<<FINSEP
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:Arial,sans-serif; background:#0d0d0d; color:#fff; height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; }
.badge { background:#9b7ff4; color:#fff; font-size:11px; padding:4px 14px; border-radius:20px; margin-bottom:24px; letter-spacing:1px; text-transform:uppercase; }
.name { font-size:38px; font-weight:800; letter-spacing:-1px; margin-bottom:12px; }
.accent-line { width:60px; height:4px; background:#9b7ff4; margin:0 auto 20px; }
.desc { font-size:14px; opacity:.5; max-width:460px; line-height:1.6; }
</style>
</head>
<body>
<div class="badge">Versión Final</div>
<div class="name">{$final_name_safe}</div>
<div class="accent-line"></div>
<div class="desc">Diseño final aprobado para {$project_name_safe}<br>Incorpora el feedback del cliente</div>
</body>
</html>
FINSEP;

    $final_sep_file = $tmp_dir . '/04_final_sep.html';
    $final_sep_pdf  = $tmp_dir . '/04_final_sep.pdf';
    file_put_contents($final_sep_file, $final_sep_html);
    $cmd = escapeshellarg($wkhtmltopdf_bin) . " {$base_opts} " . escapeshellarg($final_sep_file) . " " . escapeshellarg($final_sep_pdf) . " 2>/dev/null";
    run_cmd($cmd);
    if (file_exists($final_sep_pdf) && filesize($final_sep_pdf) > 100) $pdf_files[] = $final_sep_pdf;

    $final_prop_file = $tmp_dir . '/04_final_prop.html';
    $final_prop_pdf  = $tmp_dir . '/04_final_prop.pdf';
    $final_mod = str_replace(
        '</head>',
        '<style>html,body{zoom:0.65;-webkit-text-size-adjust:none}body{overflow:hidden}</style></head>',
        $p['proposal_final']
    );
    file_put_contents($final_prop_file, $final_mod);
    $cmd = escapeshellarg($wkhtmltopdf_bin) . " {$land_opts} " . escapeshellarg($final_prop_file) . " " . escapeshellarg($final_prop_pdf) . " 2>/dev/null";
    run_cmd($cmd);
    if (file_exists($final_prop_pdf) && filesize($final_prop_pdf) > 100) $pdf_files[] = $final_prop_pdf;
}

if (empty($pdf_files)) {
    http_response_code(500);
    echo 'Error generando PDF. Verifica que wkhtmltopdf funcione correctamente en el servidor.';
    exit;
}

// Merge con qpdf (si está disponible)
$final_pdf = $tmp_dir . '/final.pdf';
if ($qpdf_bin && count($pdf_files) > 1) {
    $files_arg = implode(' ', array_map('escapeshellarg', $pdf_files));
    $cmd = escapeshellarg($qpdf_bin) . " --empty --pages {$files_arg} -- " . escapeshellarg($final_pdf) . " 2>/dev/null";
    run_cmd($cmd);
}

if (!file_exists($final_pdf) || filesize($final_pdf) < 100) {
    // Fallback: si solo hay un PDF o qpdf falló, usar el que esté disponible
    $final_pdf = $pdf_files[count($pdf_files) - 1];
}

$filename = ($has_final ? 'Propuesta_Final_' : 'Propuestas_') . $project . '_DIMARK.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($final_pdf));
readfile($final_pdf);
