<?php
declare(strict_types=1);

/**
 * modules/corporates/view.php
 *
 * Corporate account profile page with:
 *  - Corporate details (contact & billing)
 *  - Credit & terms
 *  - Activity snapshot (recent bookings, invoices) — shown if those tables/columns exist
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch corporate
 *  3) Derived analytics (bookings & invoices) — best-effort, safe if columns/tables missing
 *  4) Render view
 */

////////////////////////////////////////////////////////////////
// 1) Bootstrap & guards
////////////////////////////////////////////////////////////////
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops','sales']);

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

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) redirect(url_modules('corporates/list.php'));

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch corporate
////////////////////////////////////////////////////////////////
$sel = db()->prepare("
  SELECT *
    FROM corporates
   WHERE id = :id AND company_id = :cid
   LIMIT 1
");
$sel->execute([':id' => $id, ':cid' => $cid]);
$corp = $sel->fetch();
if (!$corp) {
  redirect(url_modules('corporates/list.php'));
}

////////////////////////////////////////////////////////////////
// 3) Derived analytics (safe tries)
//    We try to pull related bookings & invoices if schema supports it.
//    If the query fails (missing column/table), we simply skip the section.
////////////////////////////////////////////////////////////////

$recentBookings = [];
$bookSummary = [
  'count' => 0,
  'revenue' => 0.00,
];

try {
  // Check if bookings.corporate_id exists
  $chk = db()->prepare("
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'bookings'
       AND COLUMN_NAME = 'corporate_id'
  ");
  $chk->execute();
  $hasCorporateIdInBookings = ((int)$chk->fetchColumn()) > 0;

  if ($hasCorporateIdInBookings) {
    // Recent bookings (limit 10)
    $bq = db()->prepare("
      SELECT id, booking_ref, pickup_date, pickup_time, client_name,
             total_client_price, status
        FROM bookings
       WHERE company_id = :cid
         AND corporate_id = :corp
       ORDER BY pickup_date DESC, id DESC
       LIMIT 10
    ");
    $bq->execute([':cid' => $cid, ':corp' => $id]);
    $recentBookings = $bq->fetchAll();

    // Summary
    $bs = db()->prepare("
      SELECT COUNT(*) AS c, SUM(total_client_price) AS s
        FROM bookings
       WHERE company_id = :cid AND corporate_id = :corp
    ");
    $bs->execute([':cid' => $cid, ':corp' => $id]);
    $row = $bs->fetch();
    $bookSummary['count']   = (int)($row['c'] ?? 0);
    $bookSummary['revenue'] = (float)($row['s'] ?? 0);
  }
} catch (Throwable $e) {
  // ignore — schema might not be ready
}

$recentInvoices = [];
$invSummary = [
  'count' => 0,
  'unpaid' => 0.00,
];
try {
  // Check if invoices table exists and has corporate_id
  $chk2 = db()->prepare("
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'invoices'
       AND COLUMN_NAME = 'corporate_id'
  ");
  $chk2->execute();
  $hasCorporateIdInInvoices = ((int)$chk2->fetchColumn()) > 0;

  if ($hasCorporateIdInInvoices) {
    $iq = db()->prepare("
      SELECT id, invoice_no, issue_date, total_amount, status
        FROM invoices
       WHERE company_id = :cid
         AND corporate_id = :corp
       ORDER BY issue_date DESC, id DESC
       LIMIT 10
    ");
    $iq->execute([':cid' => $cid, ':corp' => $id]);
    $recentInvoices = $iq->fetchAll();

    $is = db()->prepare("
      SELECT COUNT(*) AS c,
             SUM(CASE WHEN status IN ('Pending','Sent') THEN total_amount ELSE 0 END) AS up
        FROM invoices
       WHERE company_id = :cid AND corporate_id = :corp
    ");
    $is->execute([':cid' => $cid, ':corp' => $id]);
    $row = $is->fetch();
    $invSummary['count']  = (int)($row['c'] ?? 0);
    $invSummary['unpaid'] = (float)($row['up'] ?? 0);
  }
} catch (Throwable $e) {
  // ignore
}

////////////////////////////////////////////////////////////////
// 4) Render view
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';

function badge_cycle(string $cycle): string {
  $map = ['weekly' => 'info', 'monthly' => 'secondary'];
  $cls = $map[strtolower($cycle)] ?? 'secondary';
  return '<span class="badge text-bg-'.$cls.'">'.e(ucfirst($cycle)).'</span>';
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Corporate Account — <?= e($corp['name']) ?></h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('corporates/edit.php?id='.(int)$corp['id'])) ?>" class="btn btn-outline-primary">Edit</a>
    <form method="post" action="<?= e(url_modules('corporates/delete.php')) ?>" class="d-inline" onsubmit="return confirm('Delete this corporate account?');">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="id" value="<?= (int)$corp['id'] ?>">
      <button class="btn btn-outline-danger">Delete</button>
    </form>
    <a href="<?= e(url_modules('corporates/list.php')) ?>" class="btn btn-outline-secondary">Back</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div><?php endif; ?>

<div class="row g-3">
  <!-- Profile -->
  <div class="col-12 col-lg-7">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Corporate Details</h2>
        <dl class="row mb-0">
          <dt class="col-sm-4">Company Name</dt>
          <dd class="col-sm-8"><?= e($corp['name'] ?? '—') ?></dd>

          <dt class="col-sm-4">Contact Person</dt>
          <dd class="col-sm-8"><?= e($corp['contact_person'] ?? '—') ?></dd>

          <dt class="col-sm-4">Phone</dt>
          <dd class="col-sm-8"><?= e($corp['phone'] ?? '—') ?></dd>

          <dt class="col-sm-4">Email</dt>
          <dd class="col-sm-8"><?= e($corp['email'] ?? '—') ?></dd>

          <dt class="col-sm-4">Billing Address</dt>
          <dd class="col-sm-8"><?= nl2br(e($corp['billing_address'] ?? '—')) ?></dd>
        </dl>

        <?php if (!empty($corp['notes'])): ?>
          <hr class="my-3">
          <h2 class="h6 text-uppercase text-muted mb-2">Notes</h2>
          <div class="border rounded p-2 bg-light"><?= nl2br(e($corp['notes'])) ?></div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Credit & Terms + Snapshot -->
  <div class="col-12 col-lg-5">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Credit & Terms</h2>
        <div class="row g-3">
          <div class="col-6">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Invoice Cycle</div>
              <div class="fw-bold">
                <?= badge_cycle((string)($corp['invoice_cycle'] ?? 'monthly')) ?>
              </div>
            </div>
          </div>
          <div class="col-6">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Payment Terms</div>
              <div class="fw-bold"><?= e($corp['payment_terms'] ?? '30 days') ?></div>
            </div>
          </div>
          <div class="col-6">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Credit Limit</div>
              <div class="fw-bold">£<?= number_format((float)($corp['credit_limit'] ?? 0), 2) ?></div>
            </div>
          </div>
          <div class="col-6">
            <div class="p-2 border rounded bg-light">
              <div class="small text-muted">Created</div>
              <div class="fw-bold"><?= e((string)($corp['created_at'] ?? '')) ?></div>
            </div>
          </div>
        </div>

        <?php if ($bookSummary['count'] > 0 || $invSummary['count'] > 0): ?>
          <hr class="my-3">
          <h2 class="h6 text-uppercase text-muted mb-2">Snapshot</h2>
          <div class="row g-3">
            <?php if ($bookSummary['count'] > 0): ?>
              <div class="col-6">
                <div class="p-2 border rounded bg-light">
                  <div class="small text-muted">Bookings (total)</div>
                  <div class="fw-bold"><?= (int)$bookSummary['count'] ?></div>
                </div>
              </div>
              <div class="col-6">
                <div class="p-2 border rounded bg-light">
                  <div class="small text-muted">Revenue (sum)</div>
                  <div class="fw-bold">£<?= number_format((float)$bookSummary['revenue'], 2) ?></div>
                </div>
              </div>
            <?php endif; ?>
            <?php if ($invSummary['count'] > 0): ?>
              <div class="col-6">
                <div class="p-2 border rounded bg-light">
                  <div class="small text-muted">Invoices (count)</div>
                  <div class="fw-bold"><?= (int)$invSummary['count'] ?></div>
                </div>
              </div>
              <div class="col-6">
                <div class="p-2 border rounded bg-light">
                  <div class="small text-muted">Unpaid (est.)</div>
                  <div class="fw-bold">£<?= number_format((float)$invSummary['unpaid'], 2) ?></div>
                </div>
              </div>
            <?php endif; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<?php if (!empty($recentBookings)): ?>
  <div class="card shadow-sm mt-3">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h2 class="h6 mb-0">Recent Bookings</h2>
        <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('bookings/list.php')) ?>">Go to Bookings</a>
      </div>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead class="table-light">
            <tr>
              <th>Ref</th>
              <th>Pickup</th>
              <th>Client</th>
              <th class="text-end">Client £</th>
              <th>Status</th>
              <th style="width:80px;"></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recentBookings as $b): ?>
              <tr>
                <td><?= e($b['booking_ref'] ?? ('#'.$b['id'])) ?></td>
                <td><?= e(trim(($b['pickup_date'] ?? '').' '.($b['pickup_time'] ?? ''))) ?></td>
                <td><?= e($b['client_name'] ?? '—') ?></td>
                <td class="text-end">£<?= number_format((float)($b['total_client_price'] ?? 0), 2) ?></td>
                <td><span class="badge text-bg-secondary"><?= e($b['status'] ?? '—') ?></span></td>
                <td>
                  <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('bookings/edit.php?id='.(int)$b['id'])) ?>">Open</a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php endif; ?>

<?php if (!empty($recentInvoices)): ?>
  <div class="card shadow-sm mt-3">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h2 class="h6 mb-0">Recent Invoices</h2>
        <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('invoices/list.php')) ?>">Go to Invoices</a>
      </div>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead class="table-light">
            <tr>
              <th>No.</th>
              <th>Date</th>
              <th class="text-end">Total</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recentInvoices as $inv): ?>
              <tr>
                <td><?= e($inv['invoice_no'] ?? '#'.$inv['id']) ?></td>
                <td><?= e($inv['issue_date'] ?? '—') ?></td>
                <td class="text-end">£<?= number_format((float)($inv['total_amount'] ?? 0), 2) ?></td>
                <td><span class="badge text-bg-secondary"><?= e($inv['status'] ?? '—') ?></span></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php endif; ?>

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