<?php
declare(strict_types=1);

/**
 * modules/accounts/pnl_multisegment.php
 *
 * Multi-Segment Profit & Loss Report
 * Shows Chauffeur, Rent, Untagged, and Total columns for any period.
 * Supports: date range / month / year filters + printable layout.
 */

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

/////////////////////////////////////////////////////////
// 1. Period filters (month | year | range)
/////////////////////////////////////////////////////////
$today = new DateTimeImmutable('today');
$period = (string)($_GET['period'] ?? 'month');

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

if ($period === 'month' && isset($_GET['month']) && preg_match('/^\d{4}-\d{2}$/', $_GET['month'])) {
  $from = DateTimeImmutable::createFromFormat('Y-m-d', $_GET['month'].'-01');
  $to   = $from->modify('last day of this month');
} elseif ($period === 'year' && isset($_GET['year'])) {
  $year = (int)$_GET['year'];
  $from = new DateTimeImmutable("$year-01-01");
  $to   = new DateTimeImmutable("$year-12-31");
} elseif ($period === 'range' && isset($_GET['from'], $_GET['to'])) {
  $from = new DateTimeImmutable($_GET['from']);
  $to   = new DateTimeImmutable($_GET['to']);
}

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

/////////////////////////////////////////////////////////
// 2. Account code groupings
/////////////////////////////////////////////////////////
$incomeMap = [
  'Chauffeur Income' => ['CHAUF_INCOME'],
  'Rental Income'    => ['RENTAL_INCOME'],
  'Other Income'     => ['OTHER_INCOME'],
];

$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'],
];

/////////////////////////////////////////////////////////
// 3. Helper: segment sum
/////////////////////////////////////////////////////////
function seg_sum(int $cid, string $from, string $to, string $type, array $codes, ?string $segment): float {
  $w = ["company_id = :cid", "`date` BETWEEN :f AND :t", "type = :type"];
  $a = [':cid'=>$cid, ':f'=>$from, ':t'=>$to, ':type'=>$type];
  $accSql = '';
  if ($codes) {
    $p = [];
    foreach ($codes as $i=>$c) { $k=":c$i"; $p[]=$k; $a[$k]=$c; }
    $accSql = " AND account_code IN(".implode(',',$p).")";
  }
  if ($segment === 'Chauffeur' || $segment === 'Rent') {
    $w[] = "segment = :seg";
    $a[':seg'] = $segment;
  } elseif ($segment === 'Untagged') {
    $w[] = "(segment IS NULL OR segment = '')";
  }
  $sql = "SELECT COALESCE(SUM(amount),0) FROM transactions WHERE ".implode(' AND ',$w).$accSql;
  try { $st=db()->prepare($sql);$st->execute($a);return (float)$st->fetchColumn(); }catch(Throwable){return 0.0;}
}

/////////////////////////////////////////////////////////
// 4. Compute
/////////////////////////////////////////////////////////
$segments = ['Chauffeur','Rent','Untagged'];
function group_rows(int $cid,string $from,string $to,array $map,string $type,array $segments):array{
  $rows=[];
  foreach($map as $label=>$codes){
    $sums=[];
    $total=0;
    foreach($segments as $seg){
      $val=seg_sum($cid,$from,$to,$type,$codes,$seg);
      $sums[$seg]=$val;$total+=$val;
    }
    $rows[]=['label'=>$label]+$sums+['Total'=>$total];
  }
  return $rows;
}
$incomeRows=group_rows($cid,$fromYmd,$toYmd,$incomeMap,'income',$segments);
$cogsRows  =group_rows($cid,$fromYmd,$toYmd,$cogsMap,'expense',$segments);
$opexRows  =group_rows($cid,$fromYmd,$toYmd,$opexMap,'expense',$segments);

function col_sum(array $rows,string $col):float{
  $sum=0;foreach($rows as $r){$sum+=$r[$col]??0;}return $sum;
}
$totals=[];
foreach([...$segments,'Total'] as $col){
  $totals['income'][$col]=col_sum($incomeRows,$col);
  $totals['cogs'][$col]  =col_sum($cogsRows,$col);
  $totals['opex'][$col]  =col_sum($opexRows,$col);
  $totals['gross'][$col]=$totals['income'][$col]-$totals['cogs'][$col];
  $totals['net'][$col]=$totals['gross'][$col]-$totals['opex'][$col];
}

/////////////////////////////////////////////////////////
// 5. Render
/////////////////////////////////////////////////////////
include dirname(__DIR__,2).'/includes/header.php';
$companyName="Brownhill Group Limited";
$companyAddr="Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ";
$companyWeb="www.brown-hillchauffeurs.co.uk";
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Multi-Segment Profit &amp; Loss</h1>
    <div class="text-muted"><?= e($fromYmd) ?> → <?= e($toYmd) ?></div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/index.php')) ?>">↩ Dashboard</a>
    <button class="btn btn-dark" onclick="window.print()">🖨 Print Report</button>
  </div>
</div>

<form method="get" class="row g-2 align-items-end mb-3">
  <div class="col-md-2">
    <label class="form-label">Mode</label>
    <select class="form-select" name="period" id="periodSelect">
      <option value="month" <?= $period==='month'?'selected':'' ?>>Month</option>
      <option value="year" <?= $period==='year'?'selected':'' ?>>Year</option>
      <option value="range" <?= $period==='range'?'selected':'' ?>>Date Range</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-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 js-range" style="<?= $period==='range'?'':'display:none' ?>">
    <label class="form-label">From</label>
    <input type="date" class="form-control" name="from" value="<?= e($fromYmd) ?>">
  </div>
  <div class="col-md-2 js-range" style="<?= $period==='range'?'':'display:none' ?>">
    <label class="form-label">To</label>
    <input type="date" class="form-control" name="to" value="<?= e($toYmd) ?>">
  </div>
  <div class="col-md-2"><button class="btn btn-dark w-100">Apply</button></div>
</form>

<div class="card shadow-sm">
  <div class="card-body table-responsive">
    <table class="table table-bordered align-middle">
      <thead class="table-light text-center">
        <tr>
          <th>Account</th>
          <th>Chauffeur</th>
          <th>Rent</th>
          <th>Untagged</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        <tr><th colspan="5" class="bg-light">Operating Income</th></tr>
        <?php foreach($incomeRows as $r): ?>
          <tr><td><?= e($r['label']) ?></td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($r[$c],2) ?></td><?php endforeach; ?></tr>
        <?php endforeach; ?>
        <tr class="fw-semibold"><td>Total Income</td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($totals['income'][$c],2) ?></td><?php endforeach; ?></tr>

        <tr><th colspan="5" class="bg-light">Cost of Goods Sold</th></tr>
        <?php foreach($cogsRows as $r): ?>
          <tr><td><?= e($r['label']) ?></td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($r[$c],2) ?></td><?php endforeach; ?></tr>
        <?php endforeach; ?>
        <tr class="fw-semibold"><td>Total COGS</td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($totals['cogs'][$c],2) ?></td><?php endforeach; ?></tr>

        <tr class="table-group-divider"><td colspan="5"></td></tr>
        <tr class="fw-bold bg-secondary text-white"><td>Gross Profit</td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($totals['gross'][$c],2) ?></td><?php endforeach; ?></tr>

        <tr><th colspan="5" class="bg-light">Operating Expenses</th></tr>
        <?php foreach($opexRows as $r): ?>
          <tr><td><?= e($r['label']) ?></td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($r[$c],2) ?></td><?php endforeach; ?></tr>
        <?php endforeach; ?>
        <tr class="fw-semibold"><td>Total OPEX</td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($totals['opex'][$c],2) ?></td><?php endforeach; ?></tr>

        <tr class="table-group-divider"><td colspan="5"></td></tr>
        <tr class="fw-bold bg-dark text-white"><td>Net Profit</td>
          <?php foreach([...$segments,'Total'] as $c): ?><td class="text-end">£<?= number_format($totals['net'][$c],2) ?></td><?php endforeach; ?></tr>
      </tbody>
    </table>
  </div>
</div>

<style>
@media print {
  body { background:#fff; }
  .btn, form, .d-flex.justify-content-between { display:none !important; }
  h1 { font-size:20pt; }
  .table td, .table th { font-size:10pt; }
  @page { margin: 1cm; }
  header::before {
    content: url('<?= e(url_public("assets/logo.png")) ?>');
    display:block; margin-bottom:10px;
  }
}
</style>

<?php include dirname(__DIR__,2).'/includes/footer.php'; ?>
<script>
(function(){
  const sel=document.getElementById('periodSelect');
  const show=(cls,on)=>document.querySelectorAll('.'+cls).forEach(e=>e.style.display=on?'':'none');
  function upd(){
    const v=sel.value;
    show('js-month',v==='month');
    show('js-year',v==='year');
    show('js-range',v==='range');
  }
  sel?.addEventListener('change',upd); upd();
})();
</script>
