<?php
declare(strict_types=1);

/**
 * modules/accounts/settings/index.php
 *
 * Accounts Settings — landing / overview.
 * - Shows quick status for COA, required system mappings, and receipt storage.
 * - Provides clear links to P&L, Ledger, Income, Expenses, and COA Mapping.
 */

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

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

////////////////////////////////////////////////////////////////////////
// Small helpers
////////////////////////////////////////////////////////////////////////
function table_exists_local(string $name): bool {
  try {
    $q = db()->query("SHOW TABLES LIKE " . db()->quote($name));
    return (bool)$q->fetchColumn();
  } catch (Throwable $e) { return false; }
}
function count_coa_for_company(int $cid): int {
  try {
    $q = db()->prepare("SELECT COUNT(*) FROM chart_of_accounts WHERE company_id = :cid");
    $q->execute([':cid'=>$cid]);
    return (int)$q->fetchColumn();
  } catch (Throwable $e) { return 0; }
}
function load_map_for_company(int $cid): array {
  if (!table_exists_local('system_coa_map')) return [];
  $q = db()->prepare("SELECT event_key, account_code FROM system_coa_map WHERE company_id=:cid");
  $q->execute([':cid'=>$cid]);
  $m = [];
  foreach ($q->fetchAll() as $r) $m[(string)$r['event_key']] = (string)$r['account_code'];
  return $m;
}
function dir_status(string $abs): array {
  $exists = is_dir($abs);
  $writable = $exists ? is_writable($abs) : false;
  return [$exists, $writable];
}

// Required mappings the system uses for auto-postings
$REQUIRED_EVENTS = [
  'booking_income'     => 'Booking Income (Chauffeur)',
  'rental_income'      => 'Rental Income',
  'partner_commission' => 'Partner Commission (COGS)',
  'driver_payout'      => 'Driver Payout (COGS)',
];

// Gather status
$hasCoaTable   = table_exists_local('chart_of_accounts');
$hasMapTable   = table_exists_local('system_coa_map');
$coaCount      = $hasCoaTable ? count_coa_for_company($cid) : 0;
$currentMap    = $hasMapTable ? load_map_for_company($cid) : [];

$mappedCount = 0;
foreach ($REQUIRED_EVENTS as $k => $_) {
  if (!empty($currentMap[$k])) $mappedCount++;
}

// Receipt uploads folder check (used by expenses upload)
$receiptsRel = 'uploads/receipts';
$receiptsAbs = dirname(__DIR__, 3) . '/public/' . $receiptsRel;
[$dirExists, $dirWritable] = dir_status($receiptsAbs);

include dirname(__DIR__, 3) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Accounts Settings</h1>
    <div class="text-muted">Configure posting rules and check your accounting setup at a glance.</div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/index.php')) ?>">← Accounts Dashboard</a>
  </div>
</div>

<?php if (!$hasCoaTable): ?>
  <div class="alert alert-warning">
    <strong>Heads up:</strong> <code>chart_of_accounts</code> table not found. Create it and seed your COA to continue.
  </div>
<?php endif; ?>

<?php if (!$hasMapTable): ?>
  <div class="alert alert-warning">
    <strong>Heads up:</strong> <code>system_coa_map</code> table not found. Create it to store your event → COA mappings.
  </div>
<?php endif; ?>

<div class="row g-3">
  <!-- COA status -->
  <div class="col-12 col-xl-4">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start">
          <div>
            <div class="small text-muted text-uppercase">Chart of Accounts</div>
            <div class="display-6"><?= number_format($coaCount) ?></div>
          </div>
          <span class="badge text-bg-<?= $coaCount > 0 ? 'success' : 'secondary' ?>">
            <?= $coaCount > 0 ? 'Ready' : 'Empty' ?>
          </span>
        </div>
        <div class="text-muted small mt-2">
          Your COA powers the P&amp;L and Ledger. Make sure you have
          <code>CHAUF_INCOME</code>, <code>RENTAL_INCOME</code>, <code>PARTNER_COMM</code>, <code>DRIVER_PAYOUT</code>
          (or equivalents).
        </div>
        <div class="mt-3">
          <a href="<?= e(url_modules('accounts/settings/coamap.php')) ?>" class="btn btn-dark w-100">Open COA Mapping</a>
        </div>
      </div>
    </div>
  </div>

  <!-- Mapping status -->
  <div class="col-12 col-xl-5">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start">
          <div>
            <div class="small text-muted text-uppercase">System Mapping</div>
            <div class="h3 mb-0"><?= (int)$mappedCount ?> / <?= count($REQUIRED_EVENTS) ?> mapped</div>
          </div>
          <span class="badge text-bg-<?= $mappedCount === count($REQUIRED_EVENTS) ? 'success' : 'warning' ?>">
            <?= $mappedCount === count($REQUIRED_EVENTS) ? 'Complete' : 'Needs attention' ?>
          </span>
        </div>

        <ul class="list-group list-group-flush mt-3">
          <?php foreach ($REQUIRED_EVENTS as $key => $label):
            $set = !empty($currentMap[$key]);
          ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <span><?= e($label) ?> <code class="text-muted">[<?= e($key) ?>]</code></span>
              <span class="badge rounded-pill text-bg-<?= $set ? 'success' : 'secondary' ?>">
                <?= $set ? e($currentMap[$key]) : 'Not set' ?>
              </span>
            </li>
          <?php endforeach; ?>
        </ul>

        <div class="mt-3 d-flex gap-2">
          <a href="<?= e(url_modules('accounts/settings/coamap.php')) ?>" class="btn btn-outline-primary">Edit Mapping</a>
          <a href="<?= e(url_modules('accounts/pnl.php')) ?>" class="btn btn-outline-secondary">Preview P&amp;L</a>
        </div>
      </div>
    </div>
  </div>

  <!-- Receipts storage -->
  <div class="col-12 col-xl-3">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="small text-muted text-uppercase">Receipt Storage</div>
        <div class="mt-2">
          <div class="d-flex align-items-center justify-content-between">
            <span>Folder</span>
            <code class="small"><?= e($receiptsRel) ?></code>
          </div>
          <div class="d-flex align-items-center justify-content-between">
            <span>Exists</span>
            <span class="badge text-bg-<?= $dirExists ? 'success' : 'secondary' ?>"><?= $dirExists ? 'Yes' : 'No' ?></span>
          </div>
          <div class="d-flex align-items-center justify-content-between">
            <span>Writable</span>
            <span class="badge text-bg-<?= $dirWritable ? 'success' : 'warning' ?>"><?= $dirWritable ? 'Yes' : 'No' ?></span>
          </div>
        </div>
        <div class="text-muted small mt-2">
          Used when you upload receipts/bills in Expenses.
          <?php if (!$dirExists): ?>
            Create it: <code>public/<?= e($receiptsRel) ?></code>
          <?php endif; ?>
        </div>
        <div class="mt-3">
          <a href="<?= e(url_modules('accounts/expenses/list.php')) ?>" class="btn btn-outline-secondary w-100">Open Expenses</a>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Quick Links -->
<div class="card shadow-sm mt-3">
  <div class="card-body">
    <h2 class="h6 text-uppercase text-muted mb-2">Quick Links</h2>
    <div class="d-flex flex-wrap gap-2">
      <a class="btn btn-outline-primary" href="<?= e(url_modules('accounts/pnl.php')) ?>">📊 Profit &amp; Loss</a>
      <a class="btn btn-outline-primary" href <?= '"'.e(url_modules('accounts/ledger.php')).'"' ?>>📒 General Ledger</a>
      <a class="btn btn-outline-primary" href="<?= e(url_modules('accounts/income/list.php')) ?>">➕ Manual Income</a>
      <a class="btn btn-outline-primary" href="<?= e(url_modules('accounts/expenses/list.php')) ?>">💳 Expenses</a>
      <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/settings/coamap.php')) ?>">⚙️ COA Mapping</a>
    </div>
  </div>
</div>

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