<?php
// ============================================================
// Elegant Work — Server-side Job Card PDF Generator
// Uses wkhtmltopdf to produce a real PDF for email attachments
// ============================================================

/**
 * Generate a job card PDF and save to a temp file.
 * Returns the temp file path on success, null on failure.
 *
 * @param PDO    $db
 * @param int    $jobId
 * @param string $type   'client' | 'internal'
 * @return string|null   Path to temp .pdf file (caller must unlink after use)
 */
function generateJobCardPdf(PDO $db, int $jobId, string $type = 'client'): ?string {
    // ── 1. Generate the HTML (same logic as pdf.php) ─────────
    $html = _buildJobCardHtml($db, $jobId, $type);
    if (!$html) return null;

    // ── 2. Write HTML to temp file ───────────────────────────
    $tmpHtml = sys_get_temp_dir() . '/ewg_jc_' . $jobId . '_' . $type . '_' . uniqid() . '.html';
    $tmpPdf  = sys_get_temp_dir() . '/ewg_jc_' . $jobId . '_' . $type . '_' . uniqid() . '.pdf';

    if (file_put_contents($tmpHtml, $html) === false) return null;

    // ── 3. Run wkhtmltopdf ───────────────────────────────────
    $wk = _findWkhtmltopdf();
    if (!$wk) {
        @unlink($tmpHtml);
        return null;
    }

    $cmd = escapeshellcmd($wk)
        . ' --page-size A4'
        . ' --margin-top 15mm --margin-bottom 15mm'
        . ' --margin-left 12mm --margin-right 12mm'
        . ' --encoding UTF-8'
        . ' --no-background'
        . ' --disable-javascript'
        . ' --quiet'
        . ' ' . escapeshellarg($tmpHtml)
        . ' ' . escapeshellarg($tmpPdf)
        . ' 2>&1';

    exec($cmd, $output, $exitCode);
    @unlink($tmpHtml);

    if ($exitCode !== 0 || !file_exists($tmpPdf)) {
        error_log('[EWG PDF] wkhtmltopdf failed (exit ' . $exitCode . '): ' . implode(' | ', $output));
        @unlink($tmpPdf);
        return null;
    }

    return $tmpPdf;
}

// ── Find wkhtmltopdf binary ───────────────────────────────
function _findWkhtmltopdf(): ?string {
    $candidates = [
        '/usr/bin/wkhtmltopdf',
        '/usr/local/bin/wkhtmltopdf',
        '/opt/bin/wkhtmltopdf',
    ];
    foreach ($candidates as $c) {
        if (is_executable($c)) return $c;
    }
    // Try PATH
    $which = shell_exec('which wkhtmltopdf 2>/dev/null');
    return ($which !== null && trim($which) !== '') ? trim($which) : null;
}

// ── Build the full HTML string for a job card ─────────────
function _buildJobCardHtml(PDO $db, int $jobId, string $type): ?string {
    $isClient = $type === 'client';

    // Fetch job card
    $stmt = $db->prepare("
        SELECT jc.*, c.company_name AS client_name, c.vat_no AS client_vat,
               u.full_name AS assigned_name,
               v.registration AS vehicle_reg, v.make AS vehicle_make, v.model AS vehicle_model,
               v.cost_per_km, v.quote_rate_per_km
        FROM job_cards jc
        LEFT JOIN clients c ON c.id = jc.client_id
        LEFT JOIN users u ON u.id = jc.assigned_to
        LEFT JOIN fleet_vehicles v ON v.id = jc.vehicle_id
        WHERE jc.id = ?
    ");
    $stmt->execute([$jobId]);
    $jc = $stmt->fetch();
    if (!$jc) return null;

    // Report
    $rStmt = $db->prepare("SELECT r.*, u.full_name AS submitted_by FROM job_card_reports r LEFT JOIN users u ON u.id = r.submitted_by WHERE r.job_card_id = ?");
    $rStmt->execute([$jobId]);
    $report = $rStmt->fetch();

    // Team
    $tStmt = $db->prepare("
        SELECT u.id AS user_id, u.full_name, 'Lead Technician' AS role
        FROM users u WHERE u.id = (SELECT assigned_to FROM job_cards WHERE id = ?) AND u.id IS NOT NULL
        UNION
        SELECT u2.id, u2.full_name, COALESCE(NULLIF(jct.role,''), 'Technician') AS role
        FROM job_card_technicians jct
        JOIN users u2 ON u2.id = jct.user_id
        WHERE jct.job_card_id = ? AND jct.user_id != (SELECT assigned_to FROM job_cards WHERE id = ?)
    ");
    $tStmt->execute([$jobId, $jobId, $jobId]);
    $techs = $tStmt->fetchAll();

    // Time logs
    $tlStmt = $db->prepare("SELECT tl.*, u.full_name AS user_name FROM job_card_time_logs tl JOIN users u ON u.id = tl.user_id WHERE tl.job_card_id = ? ORDER BY tl.event_time ASC");
    $tlStmt->execute([$jobId]);
    $timeLogs = $tlStmt->fetchAll();

    // Notes
    $nStmt = $db->prepare("SELECT jcn.*, u.full_name AS user_name FROM job_card_notes jcn JOIN users u ON u.id = jcn.user_id WHERE jcn.job_card_id = ? AND jcn.is_private = 0 ORDER BY jcn.created_at ASC");
    $nStmt->execute([$jobId]);
    $notes = $nStmt->fetchAll();

    // Slips
    $slStmt = $db->prepare("SELECT s.*, u.full_name AS captured_by FROM slips s LEFT JOIN users u ON u.id = s.user_id WHERE s.job_card_id = ? ORDER BY s.slip_date");
    $slStmt->execute([$jobId]);
    $slips = $slStmt->fetchAll();

    // Stock
    $stStmt = $db->prepare("SELECT st.*, si.name AS item_name, si.unit, si.sku FROM stock_transactions st JOIN stock_items si ON si.id = st.stock_item_id WHERE st.job_card_id = ? AND st.transaction_type IN ('issue_jobcard','return') ORDER BY st.transaction_date");
    $stStmt->execute([$jobId]);
    $stockItems = $stStmt->fetchAll();

    // Net stock
    $stockNetMap = [];
    foreach ($stockItems as $si) {
        $key  = $si['stock_item_id'] . '_' . $si['unit_cost'];
        $mult = $si['transaction_type'] === 'return' ? -1 : 1;
        if (!isset($stockNetMap[$key])) {
            $stockNetMap[$key] = ['item_name' => $si['item_name'], 'sku' => $si['sku'] ?? '', 'unit' => $si['unit'] ?? '', 'unit_cost' => (float)$si['unit_cost'], 'net_qty' => 0, 'net_total' => 0];
        }
        $stockNetMap[$key]['net_qty']   += $mult * (float)$si['quantity'];
        $stockNetMap[$key]['net_total'] += $mult * (float)$si['unit_cost'] * (float)$si['quantity'];
    }
    $stockNetItems = array_values(array_filter($stockNetMap, fn($r) => $r['net_qty'] != 0));

    // Images — embedded as base64
    $imgStmt = $db->prepare("SELECT * FROM job_card_images WHERE job_card_id = ? ORDER BY created_at ASC");
    $imgStmt->execute([$jobId]);
    $images = $imgStmt->fetchAll();

    // Labour
    $defaultDays = 21.67; $defaultHours = 8.0;
    try {
        foreach ($db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group IN ('hr','finance')")->fetchAll() as $s) {
            if ($s['setting_key'] === 'working_days_per_month') $defaultDays  = (float)$s['setting_value'];
            if ($s['setting_key'] === 'working_hours_per_day')  $defaultHours = (float)$s['setting_value'];
        }
    } catch (Exception $ignored) {}

    // Calc segments (simple version)
    $drivingMin = 0; $workingMin = 0;
    $prevLog = null; $state = null;
    foreach ($timeLogs as $log) {
        if ($prevLog) {
            $mins = round((strtotime($log['event_time']) - strtotime($prevLog['event_time'])) / 60);
            if ($state === 'driving') $drivingMin += $mins;
            elseif ($state === 'working') $workingMin += $mins;
        }
        $et = $log['event_type'];
        if (in_array($et, ['depart','resume_travel'])) $state = 'driving';
        elseif (in_array($et, ['start_work','resume_work'])) $state = 'working';
        elseif (in_array($et, ['pause_work','pause_travel','arrive_base','depart_site','completed','internal_complete','invoiced'])) $state = null;
        $prevLog = $log;
    }
    $totalBillableMin = $drivingMin + $workingMin;

    $labourRows = []; $totalLabourCost = 0;
    $teamForLabour = !empty($techs) ? $techs : [];
    foreach ($teamForLabour as $tm) {
        $tid = (int)$tm['user_id'];
        $r2 = $db->prepare("SELECT es.basic_salary, es.salary_type, COALESCE(e.days_per_month,?) AS days_pm, COALESCE(e.hours_per_day,?) AS hours_pd FROM users u LEFT JOIN employees e ON e.user_id=u.id LEFT JOIN employee_salaries es ON es.employee_id=e.id WHERE u.id=? ORDER BY es.effective_date DESC LIMIT 1");
        $r2->execute([$defaultDays, $defaultHours, $tid]);
        $r2 = $r2->fetch();
        $hourlyRate = 0;
        if ($r2) {
            $dpm = (float)($r2['days_pm'] ?: $defaultDays);
            $hpd = (float)($r2['hours_pd'] ?: $defaultHours);
            if ($r2['salary_type'] === 'hourly') $hourlyRate = (float)$r2['basic_salary'];
            elseif ($r2['salary_type'] === 'monthly') { $mh = $dpm * $hpd; $hourlyRate = $mh > 0 ? round((float)$r2['basic_salary'] / $mh, 4) : 0; }
            elseif ($r2['salary_type'] === 'daily') $hourlyRate = $hpd > 0 ? round((float)$r2['basic_salary'] / $hpd, 4) : 0;
        }
        $techLabour = round(($totalBillableMin / 60) * $hourlyRate, 2);
        $totalLabourCost += $techLabour;
        $labourRows[] = ['name' => $tm['full_name'], 'role' => $tm['role'] ?? 'Technician', 'hourly_rate' => round($hourlyRate,2), 'driving_hrs' => round($drivingMin/60,2), 'working_hrs' => round($workingMin/60,2), 'total_hrs' => round($totalBillableMin/60,2), 'labour_cost' => $techLabour];
    }
    $totalLabourCost = round($totalLabourCost, 2);

    $odoStart = (int)$jc['odo_start']; $odoEnd = (int)$jc['odo_end'];
    $kmTravelled = ($odoStart && $odoEnd) ? max(0, $odoEnd - $odoStart) : 0;
    $travelCost  = $kmTravelled * (float)($jc['cost_per_km'] ?? 0);
    $slipsTotal  = array_sum(array_column($slips, 'amount'));
    $consumablesCost = 0;
    foreach ($stockNetItems as $si) $consumablesCost += $si['net_total'];

    // Company settings
    $sets = [];
    try {
        foreach ($db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group='general'")->fetchAll() as $s) {
            $sets[$s['setting_key']] = $s['setting_value'];
        }
    } catch (Exception $ignored) {}
    $company = $sets['company_name'] ?? 'Elegant Work';
    $logoPath = $sets['company_logo'] ?? null;
    $logoBase64 = null;
    if ($logoPath) {
        // Resolve from document root
        $base = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__, 2), '/');
        $logoAbsPath = $base . '/' . ltrim($logoPath, '/');
        if (file_exists($logoAbsPath)) {
            $ext  = strtolower(pathinfo($logoAbsPath, PATHINFO_EXTENSION));
            $mime = ['jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','webp'=>'image/webp','svg'=>'image/svg+xml'][$ext] ?? 'image/png';
            $logoBase64 = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($logoAbsPath));
        }
    }

    $statusLabels = ['draft'=>'Draft','assigned'=>'Assigned','travelling'=>'Travelling','on_site'=>'On Site','working'=>'Working','completed'=>'Completed','internal_complete'=>'Complete','invoiced'=>'Invoiced','no_charge'=>'No Charge','cancelled'=>'Cancelled'];
    $statusLabel  = $statusLabels[$jc['status']] ?? ucfirst($jc['status']);
    $pageTitle    = $isClient ? 'Job Completion Certificate' : 'Internal Job Card Report';

    // Inline helpers (can't use global functions — might conflict with pdf.php)
    $fmtDate = fn($d) => $d ? date('d M Y', strtotime($d)) : '—';
    $fmtDt   = fn($d) => $d ? date('d M Y H:i', strtotime($d)) : '—';
    $fmtR    = fn($n) => 'R ' . number_format((float)$n, 2);
    $esc     = fn($s) => htmlspecialchars($s ?? '', ENT_QUOTES);

    ob_start();
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $esc($pageTitle) ?> — <?= $esc($jc['job_number']) ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:Arial,Helvetica,sans-serif;font-size:11pt;color:#1a1a2e;background:#fff}
.page{max-width:780px;margin:0 auto;padding:20px}
.header{display:flex;justify-content:space-between;align-items:flex-start;padding-bottom:14px;border-bottom:3px solid #1a3a6b;margin-bottom:18px}
.company-name{font-size:20pt;font-weight:800;color:#1a3a6b}
.job-number{font-size:16pt;font-weight:800;color:#2563eb;text-align:right}
.doc-meta{font-size:9pt;color:#666;text-align:right;margin-top:4px}
.info-grid{display:grid;grid-template-columns:1fr 1fr;gap:0;margin-bottom:18px;border:1px solid #d1d5db;border-radius:6px;overflow:hidden}
.info-cell{padding:9px 12px;border-bottom:1px solid #d1d5db}
.info-label{font-size:8pt;font-weight:700;color:#6b7280;text-transform:uppercase;letter-spacing:.04em;margin-bottom:2px}
.info-value{font-size:10pt;font-weight:600;color:#111}
.section{margin-bottom:18px}
.section-title{font-size:10pt;font-weight:800;color:#1a3a6b;text-transform:uppercase;letter-spacing:.06em;padding-bottom:5px;border-bottom:2px solid #e5e7eb;margin-bottom:10px}
.text-block{background:#f9fafb;border:1px solid #e5e7eb;border-radius:5px;padding:10px 12px;font-size:10pt;line-height:1.5;white-space:pre-wrap}
table{width:100%;border-collapse:collapse;font-size:9.5pt}
th{background:#1a3a6b;color:#fff;text-align:left;padding:7px 9px;font-size:8.5pt}
td{padding:7px 9px;border-bottom:1px solid #e5e7eb;vertical-align:top}
tr:nth-child(even) td{background:#f9fafb}
.text-right{text-align:right}
.total-row td{font-weight:700;background:#eff6ff!important;border-top:2px solid #1a3a6b}
.badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:8.5pt;font-weight:700}
.badge-completed,.badge-internal_complete{background:#dcfce7;color:#166534}
.badge-invoiced{background:#dbeafe;color:#1e40af}
.badge-no_charge{background:#f0fdf4;color:#15803d}
.footer{margin-top:24px;padding-top:12px;border-top:1px solid #d1d5db;font-size:8.5pt;color:#6b7280;display:flex;justify-content:space-between}
</style>
</head>
<body>
<div class="page">

  <!-- Header -->
  <div class="header">
    <div>
      <?php if ($logoBase64): ?>
        <img src="<?= $logoBase64 ?>" alt="<?= $esc($company) ?>" style="max-height:55px;max-width:200px;object-fit:contain;display:block;margin-bottom:5px">
      <?php else: ?>
        <div class="company-name"><?= $esc($company) ?></div>
      <?php endif; ?>
      <div style="font-size:9.5pt;color:#6b7280;margin-top:3px"><?= $isClient ? 'Job Completion Certificate' : 'Internal Job Card Report' ?></div>
    </div>
    <div>
      <div class="job-number"><?= $esc($jc['job_number']) ?></div>
      <div class="doc-meta">Generated: <?= date('d M Y H:i') ?></div>
      <div style="margin-top:5px"><span class="badge badge-<?= $esc($jc['status']) ?>"><?= $esc($statusLabel) ?></span></div>
    </div>
  </div>

  <!-- Job Details -->
  <div class="section">
    <div class="section-title">Job Details</div>
    <div class="info-grid">
      <div class="info-cell"><div class="info-label">Job Title</div><div class="info-value"><?= $esc($jc['title']) ?></div></div>
      <div class="info-cell"><div class="info-label">Client</div><div class="info-value"><?= $esc($jc['client_name'] ?? '—') ?></div></div>
      <div class="info-cell"><div class="info-label">Job Type</div><div class="info-value"><?= $esc(ucfirst(str_replace('_',' ',$jc['job_type']))) ?></div></div>
      <div class="info-cell"><div class="info-label">Priority</div><div class="info-value"><?= $esc(ucfirst($jc['priority'])) ?></div></div>
      <div class="info-cell"><div class="info-label">Site</div><div class="info-value"><?= $esc($jc['site_name'] ?? '—') ?></div></div>
      <div class="info-cell"><div class="info-label">Address</div><div class="info-value"><?= $esc($jc['site_address'] ?? '—') ?></div></div>
      <div class="info-cell"><div class="info-label">Scheduled</div><div class="info-value"><?= $fmtDate($jc['scheduled_date']) ?></div></div>
      <div class="info-cell"><div class="info-label">Completed</div><div class="info-value"><?= $fmtDt($jc['completed_at']) ?></div></div>
      <?php if (!$isClient && $jc['invoice_no']): ?>
      <div class="info-cell"><div class="info-label">Invoice No.</div><div class="info-value"><?= $esc($jc['invoice_no']) ?></div></div>
      <div class="info-cell"><div class="info-label">Invoice Amount</div><div class="info-value" style="color:#1e40af;font-weight:700"><?= $jc['invoice_amount'] ? $fmtR($jc['invoice_amount']) : '—' ?></div></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Work Performed -->
  <?php if ($report && $report['work_performed']): ?>
  <div class="section">
    <div class="section-title">Work Performed</div>
    <div class="text-block"><?= $esc($report['work_performed']) ?></div>
  </div>
  <?php endif; ?>

  <?php if ($isClient): ?>
    <!-- CLIENT: Parts used (no prices) -->
    <?php if ($stockNetItems): ?>
    <div class="section">
      <div class="section-title">Parts &amp; Materials Used</div>
      <table><thead><tr><th>Item</th><th>SKU</th><th class="text-right">Qty</th><th>Unit</th></tr></thead>
      <tbody>
        <?php foreach ($stockNetItems as $si): ?>
        <tr><td><?= $esc($si['item_name']) ?></td><td><?= $esc($si['sku']) ?></td>
            <td class="text-right"><?= $si['net_qty'] == floor($si['net_qty']) ? (int)$si['net_qty'] : number_format($si['net_qty'],2) ?></td>
            <td><?= $esc($si['unit']) ?></td></tr>
        <?php endforeach; ?>
      </tbody></table>
    </div>
    <?php endif; ?>

    <!-- CLIENT: Sign-off -->
    <div class="section">
      <div class="section-title">Client Sign-Off</div>
      <div class="info-grid">
        <div class="info-cell"><div class="info-label">Signed By</div><div class="info-value"><?= $esc($report['client_name_signed'] ?? $jc['client_name_signed'] ?? '—') ?></div></div>
        <div class="info-cell"><div class="info-label">Satisfied</div><div class="info-value"><?= ($report && $report['client_satisfied']) ? '✓ Yes' : 'Not recorded' ?></div></div>
      </div>
      <?php if ($report && $report['signature_data']): ?>
        <div style="margin-top:10px;border:2px solid #d1d5db;border-radius:5px;padding:8px;min-height:80px;display:flex;align-items:center">
          <img src="<?= $report['signature_data'] ?>" style="max-height:100px;max-width:100%" alt="Signature">
        </div>
      <?php endif; ?>
    </div>

  <?php else: ?>
    <!-- INTERNAL: Cost summary -->
    <?php if ($slips || $stockNetItems || $totalLabourCost > 0 || $kmTravelled > 0): ?>
    <div class="section">
      <div class="section-title">Cost Summary</div>
      <table><thead><tr><th>Category</th><th class="text-right">Amount</th></tr></thead>
      <tbody>
        <?php if ($totalLabourCost > 0): ?><tr><td>Labour (<?= number_format($totalBillableMin/60,2) ?> hrs)</td><td class="text-right"><?= $fmtR($totalLabourCost) ?></td></tr><?php endif; ?>
        <?php if ($travelCost > 0): ?><tr><td>Travel (<?= number_format($kmTravelled) ?> km)</td><td class="text-right"><?= $fmtR($travelCost) ?></td></tr><?php endif; ?>
        <?php if ($consumablesCost > 0): ?><tr><td>Consumables / Stock</td><td class="text-right"><?= $fmtR($consumablesCost) ?></td></tr><?php endif; ?>
        <?php if ($slipsTotal > 0): ?><tr><td>Expense Slips</td><td class="text-right"><?= $fmtR($slipsTotal) ?></td></tr><?php endif; ?>
        <tr class="total-row"><td>Total Cost</td><td class="text-right"><?= $fmtR($totalLabourCost + $travelCost + $consumablesCost + $slipsTotal) ?></td></tr>
        <?php if ($jc['invoice_amount'] > 0): ?>
          <tr style="background:#f0fdf4!important"><td style="font-weight:700">Invoice Amount</td><td class="text-right" style="font-weight:700;color:#166534"><?= $fmtR($jc['invoice_amount']) ?></td></tr>
        <?php endif; ?>
      </tbody></table>
    </div>
    <?php endif; ?>

    <!-- Notes -->
    <?php if ($notes): ?>
    <div class="section">
      <div class="section-title">Notes</div>
      <table><thead><tr><th>Date</th><th>By</th><th>Note</th></tr></thead>
      <tbody><?php foreach ($notes as $n): ?><tr><td style="white-space:nowrap"><?= $fmtDt($n['created_at']) ?></td><td><?= $esc($n['user_name']) ?></td><td><?= $esc($n['note']) ?></td></tr><?php endforeach; ?></tbody>
      </table>
    </div>
    <?php endif; ?>
  <?php endif; ?>

  <!-- Footer -->
  <div class="footer">
    <span><?= $esc($company) ?> · <?= $esc($jc['job_number']) ?></span>
    <span><?= $isClient ? 'Client Copy' : 'Internal Copy — Confidential' ?> · <?= date('d M Y') ?></span>
  </div>
</div>
</body>
</html>
    <?php
    return ob_get_clean();
}