<?php
// ─── GET /api/jobcards/print-report.php?id=X&token=T ─────────────────────
// Returns a self-contained print-ready HTML page for a single jobcard.
// Opened in a new browser tab — user can Ctrl+P / Share → Print to PDF.
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Auth.php';

Auth::require();
$db = DB::get();

$id = (int)($_GET['id'] ?? 0);
if (!$id) { http_response_code(400); echo 'id required'; exit; }

// ── Fetch all data ────────────────────────────────────────────────────────

$jc = $db->row(
    "SELECT j.*, t.name AS team_name, u.username AS created_by
     FROM   jobcards j
     LEFT JOIN teams t ON t.record_id = j.team_assigned_id
     LEFT JOIN users u ON u.record_id = j.user_id
     WHERE  j.record_id = ?", [$id]
);
if (!$jc) { http_response_code(404); echo 'Not found'; exit; }

$timeline = $db->rows(
    "SELECT jt.*, u.username
     FROM   jobcard_timeline jt
     LEFT JOIN users u ON u.record_id = jt.user_id
     WHERE  jt.jobcard_id = ? ORDER BY jt.record_id ASC", [$id]
);

$notes = $db->rows(
    "SELECT * FROM notes WHERE jobcard_id = ? ORDER BY record_id ASC", [$id]
);

$payments = $db->rows(
    "SELECT jp.*, u.username
     FROM   jobcard_payments jp
     LEFT JOIN users u ON u.record_id = jp.user_id
     WHERE  jp.jobcard_id = ? ORDER BY jp.date_time ASC", [$id]
);

// ── Compute totals ────────────────────────────────────────────────────────
$totals = ['drilling' => 0, 'rieming' => 0, 'casing' => 0, 'blasting' => 0];
foreach ($timeline as $e) {
    $t = strtoupper($e['type'] ?? '');
    $m = (float)($e['meters'] ?? 0);
    if (in_array($t, ['DRILLING_STOP','DRILLING_PAUSE']))                           $totals['drilling'] += $m;
    if (in_array($t, ['RIEMING_STOP','RIEM_STOP','RIEMING_PAUSED','REIMING_STOP'])) $totals['rieming']  += $m;
    if (in_array($t, ['CASING_STOP','CASING_PAUSE']))                               $totals['casing']   += $m;
    if (in_array($t, ['BLASTING_STOP','BLASTING_PAUSE']))                           $totals['blasting'] += $m;
}
$totalMeters = array_sum($totals);
$totalPaid   = array_sum(array_column($payments, 'amount'));

// ── Helpers ───────────────────────────────────────────────────────────────
function h($v) { return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8'); }
function row($label, $value) {
    if ((string)($value ?? '') === '') return '';
    return '<tr><th>' . h($label) . '</th><td>' . h($value) . '</td></tr>';
}
function fmtMoney($v) { return 'R ' . number_format((float)$v, 2, '.', ','); }
function fmtDate($v)  { return $v ? substr($v, 0, 10) : '—'; }

$statusColor = [
    'COMPLETE'  => '#16a34a',
    'DRILLING'  => '#1d4ed8',
    'PENDING'   => '#ea580c',
    'ACTIVE'    => '#0891b2',
    'FINALISING'=> '#7c3aed',
][$jc['jc_current_status'] ?? ''] ?? '#374151';

?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Jobcard #<?= h($jc['jc_no']) ?> — Savuki Drilling</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: Arial, Helvetica, sans-serif; font-size: 11pt; color: #111; background: #fff; }
  .page { max-width: 210mm; margin: 0 auto; padding: 16mm 16mm 20mm; }

  /* Header */
  .header { display: flex; justify-content: space-between; align-items: flex-start;
            border-bottom: 3px solid #283C8C; padding-bottom: 10px; margin-bottom: 14px; }
  .header-left h1 { font-size: 20pt; color: #283C8C; font-weight: 900; }
  .header-left .sub { font-size: 9pt; color: #666; margin-top: 2px; }
  .header-right { text-align: right; }
  .header-right .jc-no { font-size: 16pt; font-weight: 800; color: #283C8C; }
  .status-badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 9pt;
                  font-weight: 700; color: #fff; background: <?= $statusColor ?>; margin-top: 4px; }

  /* Sections */
  .section { margin-bottom: 14px; }
  .section-title { font-size: 10pt; font-weight: 800; color: #283C8C; text-transform: uppercase;
                   letter-spacing: .05em; border-bottom: 1px solid #ddd; padding-bottom: 3px; margin-bottom: 6px; }
  table.info { width: 100%; border-collapse: collapse; font-size: 10pt; }
  table.info th { width: 38%; text-align: left; color: #555; font-weight: 600; padding: 2px 0; vertical-align: top; }
  table.info td { text-align: left; padding: 2px 0; vertical-align: top; }

  /* Meters strip */
  .meters-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; margin-bottom: 14px; }
  .meter-card { border: 1px solid #ddd; border-radius: 6px; padding: 8px; text-align: center; }
  .meter-card .val { font-size: 16pt; font-weight: 800; color: #283C8C; }
  .meter-card .lbl { font-size: 8pt; color: #666; margin-top: 2px; text-transform: uppercase; }
  .meter-card.total { background: #283C8C; color: #fff; }
  .meter-card.total .val, .meter-card.total .lbl { color: #fff; }
  .meter-card.paid { background: #16a34a; color: #fff; }
  .meter-card.paid .val, .meter-card.paid .lbl { color: #fff; }

  /* Timeline table */
  table.tl { width: 100%; border-collapse: collapse; font-size: 9pt; }
  table.tl th { background: #f3f4f6; font-weight: 700; padding: 4px 6px; text-align: left;
                border: 1px solid #e5e7eb; font-size: 8.5pt; }
  table.tl td { padding: 3px 6px; border: 1px solid #e5e7eb; vertical-align: top; }
  table.tl tr:nth-child(even) td { background: #fafafa; }

  /* Payments */
  table.pay { width: 100%; border-collapse: collapse; font-size: 10pt; }
  table.pay th { background: #f3f4f6; font-weight: 700; padding: 5px 8px;
                 border: 1px solid #e5e7eb; text-align: left; }
  table.pay td { padding: 4px 8px; border: 1px solid #e5e7eb; }
  table.pay .total-row td { font-weight: 800; background: #f0fdf4; color: #16a34a; }

  /* Notes */
  .note-item { border: 1px solid #e5e7eb; border-radius: 4px; padding: 6px 8px; margin-bottom: 6px; }
  .note-item .note-meta { font-size: 8.5pt; color: #888; margin-bottom: 2px; }
  .note-item .note-text { font-size: 10pt; }

  /* Footer */
  .footer { margin-top: 20px; padding-top: 8px; border-top: 1px solid #ddd;
            font-size: 8.5pt; color: #888; display: flex; justify-content: space-between; }

  /* Print */
  @media print {
    body { font-size: 10pt; }
    .no-print { display: none !important; }
    .page { padding: 8mm 10mm; max-width: none; }
    .meters-grid { break-inside: avoid; }
    table.tl { break-inside: auto; }
    table.tl tr { break-inside: avoid; }
  }

  /* Print button */
  .print-bar { position: fixed; top: 0; left: 0; right: 0; background: #283C8C; color: #fff;
               padding: 10px 20px; display: flex; justify-content: space-between; align-items: center;
               z-index: 100; box-shadow: 0 2px 8px rgba(0,0,0,.2); }
  .print-bar h2 { font-size: 12pt; }
  .btn-print { background: #F07828; color: #fff; border: none; padding: 8px 20px; border-radius: 6px;
               font-weight: 700; font-size: 11pt; cursor: pointer; }
  .btn-close  { background: rgba(255,255,255,.15); color: #fff; border: none; padding: 8px 16px;
               border-radius: 6px; font-size: 10pt; cursor: pointer; margin-left: 8px; }
  @media screen { body { padding-top: 52px; } }
</style>
</head>
<body>

<!-- Print bar -->
<div class="print-bar no-print">
  <h2>📄 Jobcard #<?= h($jc['jc_no']) ?> Report</h2>
  <div>
    <button class="btn-print" onclick="window.print()">🖨️ Print / Save as PDF</button>
    <button class="btn-close" onclick="window.close()">✕ Close</button>
  </div>
</div>

<div class="page">

  <!-- Header -->
  <div class="header">
    <div class="header-left">
      <h1>Savuki Drilling</h1>
      <div class="sub">Jobcard Report — Generated <?= date('Y-m-d H:i') ?></div>
    </div>
    <div class="header-right">
      <div class="jc-no">JC #<?= h($jc['jc_no']) ?></div>
      <div><span class="status-badge"><?= h($jc['jc_current_status'] ?? 'UNKNOWN') ?></span></div>
    </div>
  </div>

  <!-- Meter totals -->
  <div class="meters-grid">
    <div class="meter-card">
      <div class="val"><?= $totals['drilling'] > 0 ? number_format($totals['drilling'], 1) : '—' ?>m</div>
      <div class="lbl">Drilling</div>
    </div>
    <div class="meter-card">
      <div class="val"><?= $totals['rieming'] > 0 ? number_format($totals['rieming'], 1) : '—' ?>m</div>
      <div class="lbl">Rieming</div>
    </div>
    <div class="meter-card">
      <div class="val"><?= $totals['casing'] > 0 ? number_format($totals['casing'], 1) : '—' ?>m</div>
      <div class="lbl">Casing</div>
    </div>
    <div class="meter-card">
      <div class="val"><?= $totals['blasting'] > 0 ? number_format($totals['blasting'], 1) : '—' ?>m</div>
      <div class="lbl">Blasting</div>
    </div>
    <div class="meter-card total">
      <div class="val"><?= $totalMeters > 0 ? number_format($totalMeters, 1) : '—' ?>m</div>
      <div class="lbl">Total</div>
    </div>
  </div>

  <!-- Client info -->
  <div class="section">
    <div class="section-title">Client Details</div>
    <table class="info">
      <?= row('Client Name',     $jc['client_name']) ?>
      <?= row('Contact Name',    $jc['contact_name']) ?>
      <?= row('Contact Number',  $jc['contact_number']) ?>
      <?= row('Other Number',    $jc['other_number']) ?>
      <?= row('Alternate Number',$jc['alternate_number']) ?>
      <?= row('Address / Area',  $jc['address']) ?>
      <?= row('GPS Coordinates', $jc['drill_co_ordinates']) ?>
      <?= row('Slip No',         $jc['slip_no']) ?>
    </table>
  </div>

  <!-- Jobcard Info -->
  <div class="section">
    <div class="section-title">Jobcard Info</div>
    <table class="info">
      <?= row('JC Number',    $jc['jc_no']) ?>
      <?= row('Team',         $jc['team_name']) ?>
      <?= row('Status',       $jc['jc_current_status']) ?>
      <?= row('Action Date',  fmtDate($jc['action_date'])) ?>
      <?= row('Date Created', fmtDate($jc['date_created'])) ?>
      <?= row('Date Closed',  fmtDate($jc['date_time_closed'] ?? '')) ?>
      <?= row('Created By',   $jc['created_by']) ?>
    </table>
  </div>

  <!-- Drilling Results -->
  <div class="section">
    <div class="section-title">Drilling Results</div>
    <table class="info">
      <?= row('Water Strike',       $jc['water_strike'] ? $jc['water_strike'] . 'm' : '') ?>
      <?= row('Water Flow',         $jc['water_flow']) ?>
      <?= row('Interested in Pump', $jc['interested_in_pump']) ?>
      <?= row('Compressor Hours',   $jc['compressor_hours']) ?>
      <?= row('Diesel Start',       $jc['diesel_start'] ? $jc['diesel_start'] . 'L' : '') ?>
      <?= row('Diesel Stop',        $jc['diesel_stop']  ? $jc['diesel_stop']  . 'L'  : '') ?>
      <?php
        $ds = (float)($jc['diesel_start'] ?? 0);
        $de = (float)($jc['diesel_stop']  ?? 0);
        if ($ds > 0 && $de > 0) echo row('Diesel Used', number_format($ds - $de, 0) . 'L');
      ?>
      <?= row('Estimated Litres',   $jc['estimated_liters']) ?>
    </table>
  </div>

  <!-- Payments -->
  <?php if ($payments): ?>
  <div class="section">
    <div class="section-title">Payments</div>
    <table class="pay">
      <thead>
        <tr>
          <th>Method</th><th>Amount</th><th>Date</th><th>By</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($payments as $p): ?>
        <tr>
          <td><?= h($p['payment_method']) ?></td>
          <td><?= fmtMoney($p['amount']) ?></td>
          <td><?= h(substr($p['date_time'] ?? '', 0, 16)) ?></td>
          <td><?= h($p['username'] ?? '—') ?></td>
        </tr>
        <?php endforeach; ?>
        <tr class="total-row">
          <td colspan="1"><strong>Total Paid</strong></td>
          <td colspan="3"><strong><?= fmtMoney($totalPaid) ?></strong></td>
        </tr>
      </tbody>
    </table>
  </div>
  <?php endif; ?>

  <!-- Timeline -->
  <?php if ($timeline): ?>
  <div class="section">
    <div class="section-title">Timeline (<?= count($timeline) ?> entries)</div>
    <table class="tl">
      <thead>
        <tr><th>Date / Time</th><th>Type</th><th>Meters</th><th>Serial / Bit</th><th>By</th></tr>
      </thead>
      <tbody>
        <?php foreach ($timeline as $e): ?>
        <tr>
          <td><?= h(substr($e['date_time'] ?? '', 0, 16)) ?></td>
          <td><?= h($e['type'] ?? '') ?></td>
          <td><?= (float)($e['meters'] ?? 0) > 0 ? h(number_format((float)$e['meters'], 1)) . 'm' : '—' ?></td>
          <td><?= h($e['serial_number'] ?? '') ?: '—' ?></td>
          <td><?= h($e['username'] ?? '—') ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>

  <!-- Notes -->
  <?php if ($notes): ?>
  <div class="section">
    <div class="section-title">Notes (<?= count($notes) ?>)</div>
    <?php foreach ($notes as $n): ?>
    <div class="note-item">
      <div class="note-meta">
        <?= h($n['reason'] ?? '') ?><?= $n['reason'] ? ' · ' : '' ?><?= h(substr($n['date_time'] ?? '', 0, 16)) ?>
      </div>
      <div class="note-text"><?= h($n['note'] ?? '') ?></div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <!-- Footer -->
  <div class="footer">
    <span>Savuki Drilling — Confidential</span>
    <span>JC #<?= h($jc['jc_no']) ?> · <?= h($jc['jc_current_status'] ?? '') ?> · <?= date('Y-m-d H:i') ?></span>
  </div>

</div>
</body>
</html>