<?php
/**
 * send_report.php
 *
 * INVI0 DEL REPORT DI PRODUZIONE (FULL REPORT)
 * - HTML email con logo
 * - PDF completo con logo
 * - Allegato CSV
 * Versione finale pronta per SM Produce
 */

require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/../config/emailer.php';

/**
 * Invio completo della produzione (FULL REPORT)
 */
function sp_send_production_report(bool $fullReport = true): bool
{
    global $mysqli;

    if (!($mysqli instanceof mysqli)) {
        error_log('sp_send_production_report: mysqli NON valido');
        return false;
    }

    // -----------------------------------------------
    // 1) Range query
    // -----------------------------------------------
    if ($fullReport) {
        $whereSql = "";
        $title    = "Full Production Report";
    } else {
        $whereSql = "WHERE DATE(br.read_time) = CURDATE()";
        $title    = "Production Report (Today)";
    }

    $sql = "
        SELECT
            br.read_time,
            br.code,
            br.operator,
            br.station,
            br.note,

            cc.serial,
            cc.SKU,
            cc.crop,
            cc.variety,
            cc.packaging,
            cc.size,
            cc.grower,
            cc.DateTime,
            cc.shipment_id,
            cc.pallet_id
        FROM barcode_readings br
        LEFT JOIN casecodes cc ON cc.serial = br.code
        $whereSql
        ORDER BY br.read_time DESC
        LIMIT 5000
    ";

    $res = $mysqli->query($sql);
    if (!$res) {
        error_log("sp_send_production_report: Query ERROR " . $mysqli->error);
        return false;
    }

    $rows = [];
    while ($r = $res->fetch_assoc()) $rows[] = $r;
    $res->free();

    // -----------------------------------------------
    // 2) COLONNE
    // -----------------------------------------------
    $headerCols = [
        'read_time'   => 'Scan time',
        'code'        => 'Serial',
        'SKU'         => 'SKU',
        'crop'        => 'Crop',
        'variety'     => 'Variety',
        'packaging'   => 'Packaging',
        'size'        => 'Size',
        'grower'      => 'Grower',
        'DateTime'    => 'Case date/time',
        'shipment_id' => 'Shipment',
        'pallet_id'   => 'Pallet',
        'operator'    => 'Operator',
        'station'     => 'Station',
        'note'        => 'Note',
    ];

    $generated = date("Y-m-d H:i");

    // -----------------------------------------------
    // 3) LOGO
    // -----------------------------------------------
    $logoFile = __DIR__ . '/../assets/logo.png';

    $logoPdf = is_file($logoFile)
        ? '<div style="text-align:center;margin-bottom:10px;">
               <img src="file://' . $logoFile . '" style="height:60px;">
           </div>'
        : '';

    $logoEmail = 'https://smproduceprod.uk/smproduce/assets/logo.png';

    $logoEmailHtml = '<div style="text-align:center;margin-bottom:16px;">
        <img src="' . htmlspecialchars($logoEmail) . '" style="height:60px;">
    </div>';

    // -----------------------------------------------
    // 4) HTML EMAIL
    // -----------------------------------------------
    $bodyHtml  = "<div style='font-family:Arial;font-size:14px;color:#333;'>";
    $bodyHtml .= $logoEmailHtml;
    $bodyHtml .= "<h2>$title</h2>";
    $bodyHtml .= "<p><strong>Generated:</strong> $generated</p>";
    $bodyHtml .= "<p>Total scans: <strong>" . count($rows) . "</strong></p>";

    // Tabella HTML
    $bodyHtml .= "<table border='1' cellpadding='4' cellspacing='0'
                    style='border-collapse:collapse;font-size:12px;width:100%;'>";
    $bodyHtml .= "<tr>";
    foreach ($headerCols as $lbl) {
        $bodyHtml .= "<th style='background:#eee;'>" . htmlspecialchars($lbl) . "</th>";
    }
    $bodyHtml .= "</tr>";

    foreach ($rows as $r) {
        $bodyHtml .= "<tr>";
        foreach ($headerCols as $k => $lbl) {
            $val = htmlspecialchars((string)($r[$k] ?? ''), ENT_QUOTES);
            $bodyHtml .= "<td>$val</td>";
        }
        $bodyHtml .= "</tr>";
    }

    $bodyHtml .= "</table></div>";

    // -----------------------------------------------
    // 5) HTML PDF (factory)
    // -----------------------------------------------
    $pdfHtml  = "<html><body style='font-family:Arial;font-size:11px;'>";
    $pdfHtml .= $logoPdf;
    $pdfHtml .= "<h2>$title</h2>";
    $pdfHtml .= "<p><strong>Generated:</strong> $generated</p>";
    $pdfHtml .= "<p>Total scans: <strong>" . count($rows) . "</strong></p>";

    $pdfHtml .= "<table border='1' cellpadding='4' cellspacing='0'
                    style='border-collapse:collapse;font-size:10px;width:100%;'>";
    $pdfHtml .= "<tr>";
    foreach ($headerCols as $lbl) {
        $pdfHtml .= "<th style='background:#eee;'>" . htmlspecialchars($lbl) . "</th>";
    }
    $pdfHtml .= "</tr>";

    foreach ($rows as $r) {
        $pdfHtml .= "<tr>";
        foreach ($headerCols as $k => $lbl) {
            $val = htmlspecialchars((string)($r[$k] ?? ''), ENT_QUOTES);
            $pdfHtml .= "<td>$val</td>";
        }
        $pdfHtml .= "</tr>";
    }
    $pdfHtml .= "</table></body></html>";

    // -----------------------------------------------
    // 6) PDF via DOMPDF
    // -----------------------------------------------
    $autoload1 = __DIR__ . '/../lib/dompdf/autoload.inc.php';
    $autoload2 = __DIR__ . '/../lib/dompdf/autoload.php';

    if (is_file($autoload1)) require_once $autoload1;
    elseif (is_file($autoload2)) require_once $autoload2;

    if (!class_exists("Dompdf\\Dompdf")) {
        error_log("FULL REPORT: Dompdf not available");
        return false;
    }

    $dompdf = new Dompdf\Dompdf();
    $dompdf->set_option('isRemoteEnabled', true);
    $dompdf->loadHtml($pdfHtml);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->render();

    $pdfOutput = $dompdf->output();
    $tmpPdf = sys_get_temp_dir() . "/production_report_" . time() . ".pdf";
    file_put_contents($tmpPdf, $pdfOutput);

    // -----------------------------------------------
    // 7) CSV TEMP
    // -----------------------------------------------
    $tmpCsv = sys_get_temp_dir() . "/production_report_" . time() . ".csv";
    $fp = fopen($tmpCsv, "w");
    fputcsv($fp, array_values($headerCols));

    foreach ($rows as $r) {
        $line = [];
        foreach ($headerCols as $k => $lbl) {
            $line[] = $r[$k] ?? '';
        }
        fputcsv($fp, $line);
    }
    fclose($fp);

    // -----------------------------------------------
    // 8) INVIO EMAIL
    // -----------------------------------------------
    $subject = "$title - $generated";

    $ok = sp_smtp_send(
        $subject,
        $bodyHtml,
        null,
        null,
        null,
        [
            ['path' => $tmpPdf, 'name' => "production_report.pdf"],
            ['path' => $tmpCsv, 'name' => "production_report.csv"]
        ]
    );

    // Cleanup
    @unlink($tmpPdf);
    @unlink($tmpCsv);

    return $ok;
}

// =============================================================
// CALLER SECTION
// =============================================================
$full = isset($_POST['full']) ? true : false;

sp_send_production_report($full);

header("Location: production_summary.php?sent=1");
exit;

?>
