<?php
declare(strict_types=1);

/**
 * modules/accounts/pnl.php
 *
 * Profit & Loss Report — Segment-aware and PDF/CSV export
 *
 * - Period picker: month | quarter | year
 * - Segment: Chauffeur | Rent | Both
 * - Income/COGS/OPEX use fixed account-code maps (edit maps below as needed)
 * - CSV export supported
 * - PDF export supported via Dompdf if installed (composer require dompdf/dompdf)
 * - 🖨 Print view with logo, company name/address, and auto period title
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Accounts','MD','Admin','Management']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

// -----------------------------
// Period selection
// -----------------------------
$period  = (string)($_GET['period'] ?? 'month'); // month|quarter|year
$today   = new DateTimeImmutable('today');

function start_of_quarter(DateTimeImmutable $d): DateTimeImmutable {
  $m = (int)$d->format('n');
  $q = (int)ceil($m / 3);
  $firstMonth = ($q - 1) * 3 + 1;
  return DateTimeImmutable::createFromFormat('Y-m-d', $d->format('Y') . '-' . str_pad((string)$firstMonth, 2, '0', STR_PAD_LEFT) . '-01');
}
function end_of_quarter(DateTimeImmutable $d): DateTimeImmutable {
  $start = start_of_quarter($d);
  return $start->modify('+2 months')->modify('last day of this month');
}

/* defaults */
$from = $today->modify('first day of this month');
$to   = $today->modify('last day of this month');

/* month */
if ($period === 'month') {
  $monthParam = (string)($_GET['month'] ?? '');
  if ($monthParam && preg_match('/^\d{4}-\d{2}$/', $monthParam)) {
    $from = DateTimeImmutable::createFromFormat('Y-m-d', $monthParam.'-01') ?: $from;
    $to   = $from->modify('last day of this month');
  }
  $prevLabel = $from->modify('-1 month')->format('M Y');
  $nextLabel = $from->modify('+1 month')->format('M Y');
  $prevHref  = url_modules('accounts/pnl.php') . '?period=month&month=' . $from->modify('-1 month')->format('Y-m');
  $nextHref  = url_modules('accounts/pnl.php') . '?period=month&month=' . $from->modify('+1 month')->format('Y-m');
  $periodNice = 'Month — ' . $from->format('F Y');
}
/* quarter */
elseif ($period === 'quarter') {
  $year  = (int)($_GET['year'] ?? (int)$today->format('Y'));
  $q     = (int)($_GET['q']    ?? (int)ceil(((int)$today->format('n')) / 3));
  if ($q < 1 || $q > 4) $q = 1;
  $firstMonth = ($q - 1) * 3 + 1;
  $from = DateTimeImmutable::createFromFormat('Y-m-d', sprintf('%04d-%02d-01', $year, $firstMonth)) ?: start_of_quarter($today);
  $to   = $from->modify('+2 months')->modify('last day of this month');

  $prevQ = $q - 1; $prevY = $year;
  if ($prevQ < 1) { $prevQ = 4; $prevY--; }
  $nextQ = $q + 1; $nextY = $year;
  if ($nextQ > 4) { $nextQ = 1; $nextY++; }
  $prevLabel = "Q{$prevQ} {$prevY}";
  $nextLabel = "Q{$nextQ} {$nextY}";
  $prevHref  = url_modules('accounts/pnl.php') . '?period=quarter&year='.$prevY.'&q='.$prevQ;
  $nextHref  = url_modules('accounts/pnl.php') . '?period=quarter&year='.$nextY.'&q='.$nextQ;
  $periodNice = 'Quarter — Q'.$q.' '.$year;
}
/* year */
else {
  $year = (int)($_GET['year'] ?? (int)$today->format('Y'));
  $from = DateTimeImmutable::createFromFormat('Y-m-d', sprintf('%04d-01-01', $year)) ?: $today->modify('first day of January');
  $to   = DateTimeImmutable::createFromFormat('Y-m-d', sprintf('%04d-12-31', $year)) ?: $today->modify('last day of December');
  $prevLabel = (string)($year - 1);
  $nextLabel = (string)($year + 1);
  $prevHref  = url_modules('accounts/pnl.php') . '?period=year&year='.($year-1);
  $nextHref  = url_modules('accounts/pnl.php') . '?period=year&year='.($year+1);
  $periodNice = 'Year — ' . $year;
}

$fromYmd = $from->format('Y-m-d');
$toYmd   = $to->format('Y-m-d');

// -----------------------------
// Segment filter (Chauffeur / Rent / Both)
// -----------------------------
$segment = (string)($_GET['segment'] ?? 'both'); // 'chauffeur'|'rent'|'both'
$segment = strtolower($segment);
$segment = in_array($segment, ['chauffeur','rent','both'], true) ? $segment : 'both';

// -----------------------------
// Account maps (edit if needed)
// -----------------------------
// Use exact COA.code strings from your chart_of_accounts table
$incomeMap = [
  'Chauffeur Sales'   => ['CHAUF_INCOME'],
  'Car Rental Sales'  => ['RENTAL_INCOME'],
  'Other Sales'       => ['OTHER_INCOME'],
];

/**
 * IMPORTANT: Include BOTH auto partner payouts (PARTNER_PAYOUT)
 * and manual commissions (PARTNER_COMM) so both appear in COGS.
 */
$cogsMap = [
  'Commission Paid'     => ['PARTNER_PAYOUT', 'PARTNER_COMM'],
  'Driver Salaries'     => ['DRIVER_PAYOUT'],
  'Vehicle Repairs & Maintenance' => ['COGS_VEH_REPAIR_MAINT','REPAIRS_MAINT'],
];

$opexMap = [
  'Advertising & Marketing'        => ['EXP_ADV','ADV_MARKETING'],
  'Bank Fees & Charges'            => ['EXP_BANK','BANK_FEES'],
  'Congestion Charges'             => ['EXP_CONGESTION','CONGESTION'],
  'Consultant Expense'             => ['EXP_CONSULTANT','CONSULTANCY'],
  'Fines & Penalties'              => ['EXP_FINES','FINES'],
  'Fuel Expense'                   => ['EXP_FUEL','FUEL'],
  'General Expenses'               => ['EXP_GENERAL','GENERAL_EXP'],
  'Insurance'                      => ['EXP_INSURANCE','INSURANCE'],
  'Office Supplies'                => ['EXP_OFFICE','OFFICE_SUPPLIES'],
  'Parking Cost'                   => ['EXP_PARKING','PARKING_COST'],
  'Rent Expense'                   => ['EXP_RENT','RENT'],
  'Road Tax'                       => ['EXP_ROADTAX','ROAD_TAX'],
  'Salaries & Employee Wages'      => ['EXP_SALARIES','STAFF_SALARY'],
  'Subscriptions'                  => ['EXP_SUBSCRIPTIONS','SUBSCRIPTIONS'],
  'Telephone Expense'              => ['EXP_TELEPHONE','TELEPHONE'],
  'Miscellaneous Expenses'         => ['EXP_MISC','MISCELLANEOUS'],
  'Other Expenses'                 => ['EXP_OTHER','OTHER EXPENSES'],
];

// -----------------------------
// Helper: segment-aware sum query
// -----------------------------
function sum_tx(int $cid, string $from, string $to, ?string $type = null, ?array $accountCodes = null, ?string $segment = null): float {
  // Build base WHERE
  $w = ["company_id = :cid", "`date` BETWEEN :from AND :to"];
  $a = [':cid'=>$cid, ':from'=>$from, ':to'=>$to];

  if ($type !== null) {
    $w[] = "type = :type";
    $a[':type'] = $type;
  }

  // Account codes placeholder
  $accSql = '';
  if ($accountCodes && count($accountCodes) > 0) {
    $ph = [];
    foreach ($accountCodes as $i => $code) {
      $k = ":acc{$i}";
      $ph[] = $k;
      $a[$k] = $code;
    }
    $accSql = " AND account_code IN (".implode(',', $ph).")";
  }

  // Segment filter
  if ($segment !== null && $segment !== '' && strtolower($segment) !== 'both') {
    $segVal = $segment === 'chauffeur' ? 'Chauffeur' : ($segment === 'rent' ? 'Rent' : $segment);
    $w[] = "(segment = :seg)";
    $a[':seg'] = $segVal;
  }

  $sql = "SELECT COALESCE(SUM(amount),0) AS s FROM transactions WHERE ".implode(' AND ', $w).$accSql." LIMIT 1";
  try {
    $st = db()->prepare($sql);
    $st->execute($a);
    $v = $st->fetchColumn();
    return $v !== false ? (float)$v : 0.0;
  } catch (Throwable $e) {
    return 0.0;
  }
}

// -----------------------------
// Compute lines (respect segment)
// -----------------------------
$incomeLines = []; $incomeTotal = 0.0;
foreach ($incomeMap as $label => $codes) {
  $val = sum_tx($cid, $fromYmd, $toYmd, 'income', $codes, $segment === 'both' ? null : $segment);
  $incomeLines[] = ['label'=>$label, 'amount'=>$val];
  $incomeTotal  += $val;
}

$cogsLines = []; $cogsTotal = 0.0;
foreach ($cogsMap as $label => $codes) {
  $val = sum_tx($cid, $fromYmd, $toYmd, 'expense', $codes, $segment === 'both' ? null : $segment);
  $cogsLines[] = ['label'=>$label, 'amount'=>$val];
  $cogsTotal  += $val;
}
$grossProfit = $incomeTotal - $cogsTotal;

$opexLines = []; $opexTotal = 0.0;
foreach ($opexMap as $label => $codes) {
  $val = sum_tx($cid, $fromYmd, $toYmd, 'expense', $codes, $segment === 'both' ? null : $segment);
  $opexLines[] = ['label'=>$label, 'amount'=>$val];
  $opexTotal  += $val;
}
$netProfit = $grossProfit - $opexTotal;

// -----------------------------
// Export handling: CSV and PDF
// -----------------------------
$export = $_GET['export'] ?? '';

if ($export === 'csv') {
  $fn = 'pnl_'.$fromYmd.'_to_'.$toYmd.($segment !== 'both' ? '_'.$segment : '').'.csv';
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename="'.$fn.'"');
  $out = fopen('php://output','w');
  fputcsv($out, ['Profit & Loss', $fromYmd, $toYmd, 'Segment:'.($segment==='both'?'Both':ucfirst($segment))]);
  fputcsv($out, []);
  fputcsv($out, ['Income']);
  foreach ($incomeLines as $ln) fputcsv($out, [$ln['label'], number_format($ln['amount'],2,'.','')]);
  fputcsv($out, ['Total Income', number_format($incomeTotal,2,'.','')]);
  fputcsv($out, []);
  fputcsv($out, ['COGS']);
  foreach ($cogsLines as $ln) fputcsv($out, [$ln['label'], number_format($ln['amount'],2,'.','')]);
  fputcsv($out, ['Total COGS', number_format($cogsTotal,2,'.','')]);
  fputcsv($out, ['Gross Profit', number_format($grossProfit,2,'.','')]);
  fputcsv($out, []);
  fputcsv($out, ['Operating Expenses']);
  foreach ($opexLines as $ln) fputcsv($out, [$ln['label'], number_format($ln['amount'],2,'.','')]);
  fputcsv($out, ['Total OPEX', number_format($opexTotal,2,'.','')]);
  fputcsv($out, []);
  fputcsv($out, ['Net Profit', number_format($netProfit,2,'.','')]);
  fclose($out);
  exit;
}

if ($export === 'pdf') {
  // Try to generate PDF using Dompdf if available
  try {
    if (!file_exists(dirname(__DIR__,2).'/vendor/autoload.php')) {
      throw new RuntimeException('PDF export requires Dompdf (composer). Please run: composer require dompdf/dompdf');
    }
    require_once dirname(__DIR__,2).'/vendor/autoload.php';
    if (!class_exists(\Dompdf\Dompdf::class)) {
      throw new RuntimeException('Dompdf not found. Please require dompdf/dompdf via composer.');
    }

    // Build same HTML as report body (simple)
    ob_start();
    include __FILE__ . '.htmltpl.php';
    $html = ob_get_clean();

    $dompdf = new \Dompdf\Dompdf();
    $dompdf->setPaper('A4','portrait');
    $dompdf->loadHtml($html);
    $dompdf->render();
    $pdf = $dompdf->output();

    $fn = 'pnl_'.$fromYmd.'_to_'.$toYmd.($segment !== 'both' ? '_'.$segment : '').'.pdf';
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="'.$fn.'"');
    echo $pdf;
    exit;

  } catch (Throwable $e) {
    // fallback: show error message in page
    $exportError = $e->getMessage();
  }
}

// -----------------------------
// Render page
// -----------------------------
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<style>
/* ---------- PRINT STYLES (non-destructive) ---------- */
@media print {
  @page { size: A4; margin: 12mm; }
  /* Hide app chrome & buttons when printing */
  .sidebar, .app-sidebar, .navbar, .app-header, .app-footer,
  .btn, .nav, .breadcrumb, .alert, .d-print-none, .no-print { display: none !important; }

  body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
  .card, .card-body { box-shadow: none !important; }
  .table thead th { border-bottom: 1px solid #000 !important; }
  .table td, .table th { border-color: #999 !important; }
  /* Make content full width */
  .container, .container-fluid { width: 100% !important; max-width: 100% !important; padding: 0 !important; }
  /* Ensure our header shows only in print */
  .print-only { display: block !important; }
}
/* Default: hide print header on screen */
.print-only { display: none; }

/* A neat printed header */
.print-header {
  display: flex; align-items: center; gap: 16px; margin-bottom: 18px; border-bottom: 1px solid #e5e7eb; padding-bottom: 12px;
}
.print-header img { height: 54px; width: auto; }
.print-header .co-name { font-weight: 700; font-size: 18px; line-height: 1.2; }
.print-header .co-meta { font-size: 12px; color: #555; line-height: 1.35; }
.print-header .title { margin-left: auto; text-align: right; }
.print-header .title .t1 { font-weight: 700; font-size: 18px; }
.print-header .title .t2 { font-size: 12px; color: #555; }
</style>

<?php
  // Compose dynamic title for print
  $printTitle = 'Account report';
  $printSub   = $periodNice . ' — ' . $fromYmd . ' to ' . $toYmd . ' — Segment: ' . ucfirst($segment);
  $logoUrl    = url_public('assets/logo.png'); // /public/assets/logo.png
?>

<!-- PRINT-ONLY HEADER (Logo + Company + Title) -->
<div class="print-only">
  <div class="print-header">
    <img src="<?= e($logoUrl) ?>" alt="Logo">
    <div>
      <div class="co-name">Brownhill Group Limited</div>
      <div class="co-meta">
        Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ<br>
        www.brown-hillchauffeurs.co.uk
      </div>
    </div>
    <div class="title">
      <div class="t1"><?= e($printTitle) ?></div>
      <div class="t2"><?= e($printSub) ?></div>
    </div>
  </div>
</div>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Profit &amp; Loss</h1>
    <div class="text-muted"><?= e($periodNice) ?> — <?= e($fromYmd) ?> to <?= e($toYmd) ?> — Segment: <strong><?= e(ucfirst($segment)) ?></strong></div>
  </div>
  <div class="d-flex flex-wrap gap-2 no-print">
    <a class="btn btn-outline-secondary" href="<?= e($prevHref) ?>">&laquo; <?= e($prevLabel) ?></a>
    <a class="btn btn-outline-secondary" href="<?= e($nextHref) ?>"><?= e($nextLabel) ?> &raquo;</a>
    <a class="btn btn-outline-primary" href="<?= e(url_modules('accounts/pnl.php') . '?' . http_build_query(array_merge($_GET, ['export'=>'csv']))) ?>">⬇️ Export CSV</a>
    <a class="btn btn-outline-primary" href="<?= e(url_modules('accounts/pnl.php') . '?' . http_build_query(array_merge($_GET, ['export'=>'pdf']))) ?>">⬇️ Export PDF</a>
    <!-- NEW: Print button -->
    <button type="button" id="btnPrint" class="btn btn-primary">🖨 Print</button>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/index.php')) ?>">↩ Accounts Dashboard</a>
  </div>
</div>

<?php if (!empty($exportError)): ?>
  <div class="alert alert-warning no-print">
    <strong>PDF export:</strong> <?= e($exportError) ?>
    <div class="small text-muted">Install Dompdf (composer require dompdf/dompdf) to enable PDF export.</div>
  </div>
<?php endif; ?>

<!-- Top summary -->
<div class="row g-3 mb-3" id="printArea">
  <div class="col-6 col-md-3">
    <div class="card shadow-sm h-100"><div class="card-body">
      <div class="small text-muted">Income</div>
      <div class="display-6">£<?= number_format($incomeTotal,2) ?></div>
    </div></div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card shadow-sm h-100"><div class="card-body">
      <div class="small text-muted">COGS</div>
      <div class="display-6">£<?= number_format($cogsTotal,2) ?></div>
    </div></div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card shadow-sm h-100"><div class="card-body">
      <div class="small text-muted">OPEX</div>
      <div class="display-6">£<?= number_format($opexTotal,2) ?></div>
    </div></div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card shadow-sm h-100"><div class="card-body">
      <div class="small text-muted">Net Profit</div>
      <?php $badge = $netProfit >= 0 ? 'success' : 'danger'; ?>
      <div class="display-6"><span class="badge text-bg-<?= e($badge) ?>">£<?= number_format($netProfit,2) ?></span></div>
    </div></div>
  </div>
</div>

<!-- Period/Segment form -->
<div class="card shadow-sm mb-3 no-print">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-md-2">
        <label class="form-label">Period</label>
        <select class="form-select" name="period" id="periodSelect">
          <option value="month"   <?= $period==='month'  ?'selected':'' ?>>Month</option>
          <option value="quarter" <?= $period==='quarter'?'selected':'' ?>>Quarter</option>
          <option value="year"    <?= $period==='year'   ?'selected':'' ?>>Year</option>
        </select>
      </div>

      <div class="col-md-2 js-month" style="<?= $period==='month'?'':'display:none;' ?>">
        <label class="form-label">Month</label>
        <input type="month" class="form-control" name="month" value="<?= e($from->format('Y-m')) ?>">
      </div>

      <div class="col-md-2 js-quarter" style="<?= $period==='quarter'?'':'display:none;' ?>">
        <label class="form-label">Year</label>
        <input type="number" class="form-control" name="year" value="<?= e($from->format('Y')) ?>">
      </div>
      <div class="col-md-2 js-quarter" style="<?= $period==='quarter'?'':'display:none;' ?>">
        <label class="form-label">Quarter</label>
        <?php $currentQ = (int)ceil(((int)$from->format('n'))/3); ?>
        <select class="form-select" name="q">
          <?php for ($i=1;$i<=4;$i++): ?>
            <option value="<?= $i ?>" <?= $currentQ===$i?'selected':'' ?>>Q<?= $i ?></option>
          <?php endfor; ?>
        </select>
      </div>

      <div class="col-md-2 js-year" style="<?= $period==='year'?'':'display:none;' ?>">
        <label class="form-label">Year</label>
        <input type="number" class="form-control" name="year" value="<?= e($from->format('Y')) ?>">
      </div>

      <div class="col-md-2">
        <label class="form-label">Segment</label>
        <select class="form-select" name="segment">
          <option value="both" <?= $segment==='both'?'selected':'' ?>>Both</option>
          <option value="chauffeur" <?= $segment==='chauffeur'?'selected':'' ?>>Chauffeur</option>
          <option value="rent" <?= $segment==='rent'?'selected':'' ?>>Rent</option>
        </select>
      </div>

      <div class="col-md-2">
        <button class="btn btn-dark w-100">Apply</button>
      </div>
    </form>
  </div>
</div>

<!-- Report table -->
<div class="card shadow-sm">
  <div class="card-body p-0">
    <table class="table mb-0 align-middle">
      <thead class="table-light">
        <tr>
          <th>Category</th>
          <th class="text-end" style="width:220px;">Amount</th>
        </tr>
      </thead>
      <tbody>
        <tr class="table-group-divider"><td colspan="2"></td></tr>
        <tr><th colspan="2" class="bg-light">Income</th></tr>
        <?php foreach ($incomeLines as $ln): ?>
          <tr><td><?= e($ln['label']) ?></td><td class="text-end">£<?= number_format($ln['amount'],2) ?></td></tr>
        <?php endforeach; ?>
        <tr class="fw-semibold"><td>Total Income</td><td class="text-end">£<?= number_format($incomeTotal,2) ?></td></tr>

        <tr class="table-group-divider"><td colspan="2"></td></tr>
        <tr><th colspan="2" class="bg-light">Cost of Goods Sold (COGS)</th></tr>
        <?php foreach ($cogsLines as $ln): ?>
          <tr><td><?= e($ln['label']) ?></td><td class="text-end">£<?= number_format($ln['amount'],2) ?></td></tr>
        <?php endforeach; ?>
        <tr class="fw-semibold"><td>Total COGS</td><td class="text-end">£<?= number_format($cogsTotal,2) ?></td></tr>

        <tr class="table-group-divider"><td colspan="2"></td></tr>
        <?php $gpBadge = $grossProfit >= 0 ? 'success' : 'danger'; ?>
        <tr class="fw-semibold"><td>Gross Profit</td><td class="text-end"><span class="badge text-bg-<?= e($gpBadge) ?>">£<?= number_format($grossProfit,2) ?></span></td></tr>

        <tr class="table-group-divider"><td colspan="2"></td></tr>
        <tr><th colspan="2" class="bg-light">Operating Expenses</th></tr>
        <?php foreach ($opexLines as $ln): ?>
          <tr><td><?= e($ln['label']) ?></td><td class="text-end">£<?= number_format($ln['amount'],2) ?></td></tr>
        <?php endforeach; ?>
        <tr class="fw-semibold"><td>Total Operating Expenses</td><td class="text-end">£<?= number_format($opexTotal,2) ?></td></tr>

        <tr class="table-group-divider"><td colspan="2"></td></tr>
        <?php $npBadge = $netProfit >= 0 ? 'success' : 'danger'; ?>
        <tr class="fw-bold"><td>Net Profit</td><td class="text-end"><span class="badge text-bg-<?= e($npBadge) ?>">£<?= number_format($netProfit,2) ?></span></td></tr>
      </tbody>
    </table>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>

<script>
(function(){
  const sel = document.getElementById('periodSelect');
  const show = (cls, on) => document.querySelectorAll('.' + cls).forEach(el => el.style.display = on ? '' : 'none');
  function update() {
    const v = sel.value;
    show('js-month',   v === 'month');
    show('js-quarter', v === 'quarter');
    show('js-year',    v === 'year');
  }
  sel?.addEventListener('change', update);
  update();

  // 🖨 Print
  document.getElementById('btnPrint')?.addEventListener('click', function(){
    window.print();
  });
})();
</script>
