<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
auth_require_partner_portal();
$pdo = crm_pdo();
$page_title = 'Partner Portal';

$partnerId = auth_partner_id();

if (auth_is_admin_like() && $partnerId <= 0) {
    $partners = $pdo->query("SELECT id, company_name FROM external_partners WHERE active = 1 ORDER BY company_name ASC")->fetchAll();
    include __DIR__ . '/../includes/header.php';
    ?>
    <div class="page-header">
      <div class="page-header-title">
        <h1>Partner Portal</h1>
        <span>Admin access — choose partner</span>
      </div>
    </div>
    <div class="card">
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Partner</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($partners as $p): ?>
              <tr>
                <td><?php echo h($p['company_name']); ?></td>
                <td><a class="btn btn-sm btn-outline-light" href="/public/partners/my_jobs.php?partner_id=<?php echo (int)$p['id']; ?>">Open portal</a></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

if ($partnerId <= 0) {
    http_response_code(403);
    exit('Partner record not linked.');
}

$stmt = $pdo->prepare("
    SELECT pa.*, p.title, p.code, p.address, p.city, c.name AS customer_name, c.phone AS customer_phone
    FROM project_assignments pa
    JOIN projects p ON p.id = pa.project_id
    LEFT JOIN customers c ON c.id = p.customer_id
    WHERE pa.external_partner_id = :partner_id
    ORDER BY pa.assigned_date ASC, pa.assigned_time ASC, pa.id DESC
");
$stmt->execute([':partner_id' => $partnerId]);
$rows = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Partner Portal</h1>
    <span><?php echo auth_is_admin_like() ? 'Admin view' : 'Assigned jobs'; ?></span>
  </div>
</div>

<?php if (!$rows): ?>
  <div class="card"><p class="small">No assigned jobs.</p></div>
<?php else: ?>
  <div class="grid-2">
    <?php foreach ($rows as $r): ?>
      <div class="card">
        <div class="page-header-title">
          <h1 style="font-size:1.05rem"><?php echo h($r['title']); ?></h1>
          <span><?php echo h((string)$r['assigned_date'] . ' ' . substr((string)$r['assigned_time'], 0, 5)); ?></span>
        </div>
        <p><strong>Project:</strong> <?php echo h($r['code']); ?></p>
        <p><strong>Customer:</strong> <?php echo h($r['customer_name']); ?></p>
        <p><strong>Phone:</strong> <?php echo h($r['customer_phone']); ?></p>
        <p><strong>Address:</strong> <?php echo h(trim(($r['address'] ?? '') . ' ' . ($r['city'] ?? ''))); ?></p>
        <p><strong>Role:</strong> <?php echo h($r['role_label']); ?></p>
        <p><strong>Status:</strong> <?php echo h($r['status']); ?></p>
        <?php
          $quote = null;
          try {
              $qs = $pdo->prepare("SELECT quote_amount, status, updated_at FROM partner_project_costings WHERE project_id = :pid AND external_partner_id = :partner_id LIMIT 1");
              $qs->execute([':pid' => (int)$r['project_id'], ':partner_id' => (int)$partnerId]);
              $quote = $qs->fetch();
          } catch (Throwable $e) {}
        ?>
        <p><strong>My costing:</strong>
          <?php if ($quote): ?>
            € <?php echo h(number_format((float)($quote['quote_amount'] ?? 0), 2)); ?> · <?php echo h($quote['status'] ?? 'submitted'); ?>
          <?php else: ?>
            Not submitted
          <?php endif; ?>
        </p>
        <div class="form-actions">
          <a class="btn btn-sm btn-outline-light" href="/public/partners/project_costing.php?project_id=<?php echo (int)$r['project_id']; ?><?php echo auth_is_admin_like() ? '&partner_id=' . (int)$partnerId : ''; ?>">My Costing</a>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<?php include __DIR__ . '/../includes/footer.php'; ?>
