<?php
declare(strict_types=1);
/**
 * modules/accounts/pnl_multisegment_print.php
 *
 * Browser-printable view for Multi-Segment Profit & Loss report.
 * No forced PDF output — opens cleanly in browser for Ctrl+P / Save as PDF.
 */

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'));

$from   = (string)($_GET['from'] ?? '');
$to     = (string)($_GET['to'] ?? '');
$period = (string)($_GET['period'] ?? '');
if (!$from || !$to) exit('Invalid date range.');

// ---------------------------------------------------------
// Branding
// ---------------------------------------------------------
$companyName    = "Brownhill Group Limited";
$companyAddress = "Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ";
$companyWebsite = "www.brown-hillchauffeurs.co.uk";
$logoPath       = url_public('assets/logo.png');

// ---------------------------------------------------------
// Account Mappings (same as pnl_multisegment.php)
// ---------------------------------------------------------
$incomeMap = [
  'Chauffeur Sales'   => ['CHAUF_INCOME'],
  'Car Rental Sales'  => ['RENTAL_INCOME'],
  'Other Sales'       => ['OTHER_INCOME'],
];
$cogsMap = [
  'Commission Paid'   => ['PARTNER_PAYOUT','PARTNER_COMM'],
  'Driver Salaries'   => ['DRIVER_PAYOUT'],
  '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'],
];

$segments = ['Chauffeur','Rent','Untagged'];

// ---------------------------------------------------------
// Helper for summing values
// ---------------------------------------------------------
function seg_sum_print(int $cid, string $from, string $to, string $type, ?array $codes, string $seg): float {
  $w = ["company_id = :cid", "`date` BETWEEN :f AND :t", "type = :type"];
  $a = [':cid'=>$cid, ':f'=>$from, ':t'=>$to, ':type'=>$type];
  if ($codes && count($codes)) {
    $ph = [];
    foreach ($codes as $i=>$c) { $ph[":c$i"]=$c; }
    $w[] = "account_code IN (".implode(',', array_keys($ph)).")";
    $a += $ph;
  }
  if ($seg !== 'All') {
    $w[] = "(segment = :seg)";
    $a[':seg'] = $seg;
  }
  $sql = "SELECT COALESCE(SUM(amount),0) FROM transactions WHERE ".implode(' AND ',$w);
  try { $s=db()->prepare($sql);$s->execute($a);return (float)$s->fetchColumn(); }
  catch (Throwable) { return 0.0; }
}

// ---------------------------------------------------------
// Build Report Data
// ---------------------------------------------------------
$sections = [
  'Income' => [$incomeMap,'income'],
  'COGS'   => [$cogsMap,'expense'],
  'OPEX'   => [$opexMap,'expense']
];
$report = [];

foreach ($sections as $section => [$map,$type]) {
  foreach ($map as $label=>$codes) {
    $line=['label'=>$label];$total=0.0;
    foreach ($segments as $seg) {
      $val = seg_sum_print($cid,$from,$to,$type,$codes,$seg);
      $line[$seg]=$val;$total+=$val;
    }
    $line['Total']=$total;
    $report[$section][]=$line;
  }
}
$totIncome=$totCogs=$totOpex=0.0;
foreach ($report['Income'] as $r)$totIncome+=$r['Total'];
foreach ($report['COGS'] as $r)$totCogs+=$r['Total'];
foreach ($report['OPEX'] as $r)$totOpex+=$r['Total'];
$gross=$totIncome-$totCogs;
$net=$gross-$totOpex;

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Account Report — <?= e($period) ?></title>
<style>
body {
  font-family: "Segoe UI", Arial, sans-serif;
  color: #000;
  background: #fff;
  margin: 0;
  padding: 25px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 3px solid #0A3D62;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.header img { height: 70px; }
.company-info { text-align: right; font-size: 13px; line-height: 1.4; color: #333; }
h1 {
  text-align: center;
  font-size: 22px;
  margin-bottom: 4px;
  text-transform: uppercase;
  color: #0A3D62;
}
.subtitle {
  text-align: center;
  font-size: 13px;
  color: #444;
  margin-bottom: 20px;
}
table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 15px;
}
th, td {
  border: 1px solid #999;
  padding: 6px 8px;
  font-size: 13px;
}
th {
  background: #F4C542;
  color: #000;
  text-align: left;
}
td.text-end { text-align: right; }
tfoot td {
  font-weight: bold;
  background: #fafafa;
}
.section-title {
  background: #0A3D62;
  color: #fff;
  font-weight: bold;
  text-transform: uppercase;
}
.total-row {
  background: #f8f8f8;
  font-weight: bold;
}
@media print {
  @page { size: A4 portrait; margin: 15mm 12mm; }
  body { padding: 0; }
  .no-print { display: none; }
}
</style>
</head>
<body onload="window.print()">

<div class="header">
  <img src="<?= e($logoPath) ?>" alt="Logo">
  <div class="company-info">
    <strong><?= e($companyName) ?></strong><br>
    <?= e($companyAddress) ?><br>
    <?= e($companyWebsite) ?>
  </div>
</div>

<h1>Account Report</h1>
<div class="subtitle"><?= e($period) ?> &nbsp; | &nbsp; <?= e($from) ?> to <?= e($to) ?></div>

<table>
  <thead>
    <tr>
      <th>Category</th>
      <?php foreach ($segments as $s): ?><th class="text-end"><?= e($s) ?></th><?php endforeach; ?>
      <th class="text-end">Total</th>
    </tr>
  </thead>
  <tbody>

  <!-- Income -->
  <tr><td colspan="5" class="section-title">Income</td></tr>
  <?php foreach ($report['Income'] as $r): ?>
  <tr>
    <td><?= e($r['label']) ?></td>
    <?php foreach ($segments as $s): ?><td class="text-end">£<?= number_format($r[$s],2) ?></td><?php endforeach; ?>
    <td class="text-end">£<?= number_format($r['Total'],2) ?></td>
  </tr>
  <?php endforeach; ?>
  <tr class="total-row">
    <td>Total Income</td>
    <?php foreach ($segments as $s): ?><td class="text-end">£<?= number_format(array_sum(array_column($report['Income'],$s)),2) ?></td><?php endforeach; ?>
    <td class="text-end">£<?= number_format($totIncome,2) ?></td>
  </tr>

  <!-- COGS -->
  <tr><td colspan="5" class="section-title">Cost of Goods Sold (COGS)</td></tr>
  <?php foreach ($report['COGS'] as $r): ?>
  <tr>
    <td><?= e($r['label']) ?></td>
    <?php foreach ($segments as $s): ?><td class="text-end">£<?= number_format($r[$s],2) ?></td><?php endforeach; ?>
    <td class="text-end">£<?= number_format($r['Total'],2) ?></td>
  </tr>
  <?php endforeach; ?>
  <tr class="total-row">
    <td>Total COGS</td>
    <?php foreach ($segments as $s): ?><td class="text-end">£<?= number_format(array_sum(array_column($report['COGS'],$s)),2) ?></td><?php endforeach; ?>
    <td class="text-end">£<?= number_format($totCogs,2) ?></td>
  </tr>

  <!-- Gross Profit -->
  <tr class="total-row">
    <td>Gross Profit</td>
    <?php foreach ($segments as $s): ?>
      <td class="text-end">£<?= number_format(array_sum(array_column($report['Income'],$s))-array_sum(array_column($report['COGS'],$s)),2) ?></td>
    <?php endforeach; ?>
    <td class="text-end">£<?= number_format($gross,2) ?></td>
  </tr>

  <!-- OPEX -->
  <tr><td colspan="5" class="section-title">Operating Expenses</td></tr>
  <?php foreach ($report['OPEX'] as $r): ?>
  <tr>
    <td><?= e($r['label']) ?></td>
    <?php foreach ($segments as $s): ?><td class="text-end">£<?= number_format($r[$s],2) ?></td><?php endforeach; ?>
    <td class="text-end">£<?= number_format($r['Total'],2) ?></td>
  </tr>
  <?php endforeach; ?>
  <tr class="total-row">
    <td>Total OPEX</td>
    <?php foreach ($segments as $s): ?><td class="text-end">£<?= number_format(array_sum(array_column($report['OPEX'],$s)),2) ?></td><?php endforeach; ?>
    <td class="text-end">£<?= number_format($totOpex,2) ?></td>
  </tr>

  <!-- Net Profit -->
  <tr class="total-row" style="background:#E8F5E9;">
    <td>Net Profit</td>
    <?php foreach ($segments as $s): ?>
      <td class="text-end">£<?= number_format(
        (array_sum(array_column($report['Income'],$s))
        - array_sum(array_column($report['COGS'],$s))
        - array_sum(array_column($report['OPEX'],$s))),2) ?></td>
    <?php endforeach; ?>
    <td class="text-end">£<?= number_format($net,2) ?></td>
  </tr>

  </tbody>
</table>

<div class="no-print" style="margin-top:20px;text-align:center;">
  <a href="<?= e(url_modules('accounts/pnl_multisegment.php')) ?>" class="btn btn-dark">↩ Back to P&L Report</a>
</div>

</body>
</html>
