<?php
declare(strict_types=1);

/**
 * modules/partners/view.php
 *
 * Partner profile with:
 *  - Overview (contact, commission)
 *  - Activity snapshot (bookings count, revenue, commission)
 *  - Recent bookings (linked)
 *  - Quotes (if quotes table exists)
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch partner + aggregates
 *  3) Try fetch quotes (optional)
 *  4) Render
 */

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

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

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

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch partner + aggregates
////////////////////////////////////////////////////////////////
$sel = db()->prepare("
  SELECT *
    FROM partners
   WHERE id=:id AND company_id=:cid
   LIMIT 1
");
$sel->execute([':id' => $pid, ':cid' => $cid]);
$partner = $sel->fetch();
if (!$partner) redirect(url_modules('partners/list.php'));

// Activity snapshot (bookings count, revenue, commission)
$activity = [
  'bookings'    => 0,
  'revenue'     => 0.00,
  'commission'  => 0.00,
];

try {
  // If your bookings table already stores partner_commission_amount per booking, we prefer summing that.
  // Otherwise we fall back to computing from partner rule (percent/fixed) against total_client_price.
  $q = db()->prepare("
    SELECT
      COUNT(*)                                        AS cnt,
      COALESCE(SUM(b.total_client_price),0)          AS rev,
      COALESCE(SUM(
        CASE
          WHEN b.partner_commission_amount IS NOT NULL THEN b.partner_commission_amount
          WHEN p.commission_type = 'percent' THEN ROUND((p.commission_value/100.0) * COALESCE(b.total_client_price,0), 2)
          ELSE COALESCE(p.commission_value,0)
        END
      ),0)                                           AS comm
    FROM bookings b
    LEFT JOIN partners p ON p.id = b.partner_id
    WHERE b.company_id = :cid AND b.partner_id = :pid
  ");
  $q->execute([':cid'=>$cid, ':pid'=>$pid]);
  $row = $q->fetch();
  if ($row) {
    $activity['bookings']   = (int)($row['cnt']  ?? 0);
    $activity['revenue']    = (float)($row['rev'] ?? 0);
    $activity['commission'] = (float)($row['comm'] ?? 0);
  }
} catch (Throwable $e) {
  // Ignore if bookings table differs
}

// Recent bookings list (limit 10)
$recent = [];
try {
  $rb = db()->prepare("
    SELECT
      b.id, b.booking_ref, b.pickup_date, b.pickup_time,
      b.client_name, b.total_client_price, b.status
    FROM bookings b
    WHERE b.company_id = :cid AND b.partner_id = :pid
    ORDER BY b.id DESC
    LIMIT 10
  ");
  $rb->execute([':cid'=>$cid, ':pid'=>$pid]);
  $recent = $rb->fetchAll();
} catch (Throwable $e) {
  // ignore
}

////////////////////////////////////////////////////////////////
// 3) Try fetch quotes (optional)
////////////////////////////////////////////////////////////////
$quotes = [];
$quotesEnabled = true;
try {
  $rq = db()->prepare("
    SELECT id, client_name, quote_date, status, discount
      FROM quotes
     WHERE company_id=:cid AND partner_id=:pid
     ORDER BY id DESC
     LIMIT 10
  ");
  $rq->execute([':cid'=>$cid, ':pid'=>$pid]);
  $quotes = $rq->fetchAll();
} catch (Throwable $e) {
  $quotesEnabled = false; // table doesn't exist yet
}

////////////////////////////////////////////////////////////////
// Helpers (UI)
////////////////////////////////////////////////////////////////
function commission_label(array $p): string {
  $type = $p['commission_type'] ?? 'fixed';
  $val  = (float)($p['commission_value'] ?? 0);
  if ($type === 'percent') return number_format($val, 2) . '% of booking';
  return '£' . number_format($val, 2) . ' per booking';
}

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Partner — <?= e($partner['name'] ?? '—') ?></h1>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('partners/list.php')) ?>">Back</a>
    <a class="btn btn-outline-primary" href="<?= e(url_modules('partners/edit.php').'?id='.(int)$pid) ?>">Edit</a>
    <a class="btn btn-outline-danger" href="<?= e(url_modules('partners/delete.php').'?id='.(int)$pid) ?>">Delete</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; ?>

<!-- Overview / Stats -->
<div class="row g-3 mb-3">
  <div class="col-md-4">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="small text-muted text-uppercase mb-1">Bookings</div>
        <div class="display-6 mb-0"><?= number_format($activity['bookings']) ?></div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="small text-muted text-uppercase mb-1">Revenue</div>
        <div class="display-6 mb-0">£<?= number_format($activity['revenue'], 2) ?></div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <div class="small text-muted text-uppercase mb-1">Commission (Est.)</div>
        <div class="display-6 mb-0">£<?= number_format($activity['commission'], 2) ?></div>
      </div>
    </div>
  </div>
</div>

<!-- Profile + Commission -->
<div class="row g-3">
  <div class="col-lg-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Profile</h2>
        <dl class="row mb-0">
          <dt class="col-4">Company</dt><dd class="col-8"><?= e($partner['name'] ?? '—') ?></dd>
          <dt class="col-4">Contact</dt><dd class="col-8"><?= e($partner['contact_name'] ?? '—') ?></dd>
          <dt class="col-4">Phone</dt>
          <dd class="col-8">
            <?php if (!empty($partner['phone'])): ?>
              <a href="tel:<?= e($partner['phone']) ?>"><?= e($partner['phone']) ?></a>
            <?php else: ?>—<?php endif; ?>
          </dd>
          <dt class="col-4">Email</dt>
          <dd class="col-8">
            <?php if (!empty($partner['email'])): ?>
              <a href="mailto:<?= e($partner['email']) ?>"><?= e($partner['email']) ?></a>
            <?php else: ?>—<?php endif; ?>
          </dd>
          <dt class="col-4">Address</dt><dd class="col-8"><?= nl2br(e($partner['address'] ?? '—')) ?></dd>

          <?php if (!empty($partner['bank_account_name']) || !empty($partner['bank_sort_code']) || !empty($partner['bank_account_number'])): ?>
            <dt class="col-12 mt-2"><hr></dt>
            <dt class="col-4">Bank A/C Name</dt><dd class="col-8"><?= e($partner['bank_account_name'] ?? '—') ?></dd>
            <dt class="col-4">Sort Code</dt><dd class="col-8"><?= e($partner['bank_sort_code'] ?? '—') ?></dd>
            <dt class="col-4">Account No.</dt><dd class="col-8"><?= e($partner['bank_account_number'] ?? '—') ?></dd>
          <?php endif; ?>

          <dt class="col-12 mt-2"><hr></dt>
          <dt class="col-4">Created</dt><dd class="col-8"><?= e($partner['created_at'] ?? '—') ?></dd>
          <dt class="col-4">Updated</dt><dd class="col-8"><?= e($partner['updated_at'] ?? '—') ?></dd>
        </dl>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-2">Commission</h2>
        <div class="mb-2">
          <span class="badge text-bg-dark"><?= e(strtoupper((string)($partner['commission_type'] ?? 'fixed'))) ?></span>
          <span class="ms-2"><?= e(commission_label($partner)) ?></span>
        </div>
        <div class="small text-muted mb-3">
          The estimated commission above uses stored <code>partner_commission_amount</code> on each booking when available,
          otherwise calculates from partner rule.
        </div>

        <h2 class="h6 text-uppercase text-muted mb-2">Notes</h2>
        <div class="border rounded p-2 bg-light" style="min-height:88px;">
          <?= nl2br(e($partner['notes'] ?? '—')) ?>
        </div>

        <div class="mt-3 d-flex gap-2">
          <a class="btn btn-outline-primary"
             href="<?= e(url_modules('bookings/add.php').'?partner_id='.(int)$pid) ?>">
            Create Booking with Partner
          </a>
          <?php if ($quotesEnabled): ?>
          <a class="btn btn-outline-secondary"
             href="<?= e(url_modules('invoices/quote.php').'?partner_id='.(int)$pid) ?>">
            New Quote
          </a>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Recent Bookings -->
<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').'?partner_id='.(int)$pid) ?>">View All</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 class="text-end">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($recent): foreach ($recent as $r): ?>
            <tr>
              <td><?= e($r['booking_ref'] ?? '—') ?></td>
              <td><?= e(trim(($r['pickup_date'] ?? '') . ' ' . ($r['pickup_time'] ?? ''))) ?></td>
              <td><?= e($r['client_name'] ?? '—') ?></td>
              <td class="text-end">£<?= number_format((float)($r['total_client_price'] ?? 0), 2) ?></td>
              <td><span class="badge text-bg-secondary"><?= e($r['status'] ?? '—') ?></span></td>
              <td class="text-end">
                <a class="btn btn-sm btn-outline-primary"
                   href="<?= e(url_modules('bookings/edit.php').'?id='.(int)$r['id']) ?>">Open</a>
                <a class="btn btn-sm btn-outline-secondary"
                   href="<?= e(url_modules('bookings/pdf.php').'?booking_id='.(int)$r['id']) ?>">PDF</a>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="6" class="text-center text-muted">No bookings yet.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Quotes (optional) -->
<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 Quotes</h2>
      <?php if ($quotesEnabled): ?>
        <a class="btn btn-sm btn-outline-secondary"
           href="<?= e(url_modules('invoices/list.php').'?tab=quotes&partner_id='.(int)$pid) ?>">View All Quotes</a>
      <?php endif; ?>
    </div>
    <?php if (!$quotesEnabled): ?>
      <div class="alert alert-info mb-0">
        Quotes module not enabled yet. Create the <code>quotes</code> table to use this section.
      </div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead class="table-light">
            <tr>
              <th>#</th>
              <th>Client</th>
              <th>Date</th>
              <th>Status</th>
              <th class="text-end">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($quotes): foreach ($quotes as $q): ?>
              <tr>
                <td><?= (int)$q['id'] ?></td>
                <td><?= e($q['client_name'] ?? '—') ?></td>
                <td><?= e($q['quote_date'] ?? '—') ?></td>
                <td><span class="badge text-bg-secondary"><?= e($q['status'] ?? 'draft') ?></span></td>
                <td class="text-end">
                  <a class="btn btn-sm btn-outline-primary"
                     href="<?= e(url_modules('invoices/quote.php').'?id='.(int)$q['id']) ?>">Open</a>
                </td>
              </tr>
            <?php endforeach; else: ?>
              <tr><td colspan="5" class="text-center text-muted">No quotes yet.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

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