<?php
declare(strict_types=1);

Auth::requireLogin();

$id = (int) get_int('id', 0);

$company = Database::one(
    'SELECT c.*, co.name_en AS country_name, p.name AS parent_name
       FROM companies c
       LEFT JOIN countries co ON co.code = c.country_code
       LEFT JOIN companies p  ON p.id = c.parent_company_id
      WHERE c.id = :id',
    ['id' => $id]
);

if ($company === null) {
    http_response_code(404);
    Flash::add('warn', 'That company no longer exists.');
    redirect('companies', 'list');
}

$tags = Database::all(
    'SELECT t.slug, t.name_en, t.name_he, t.color, t.is_core_competition
       FROM company_tags ct JOIN tags t ON t.id = ct.tag_id
      WHERE ct.company_id = :id ORDER BY t.sort_order',
    ['id' => $id]
);

$rels = Database::all(
    'SELECT rel_type, program, region, notes FROM company_relationships
      WHERE company_id = :id ORDER BY rel_type',
    ['id' => $id]
);

$products = Database::all(
    'SELECT id, name, status, first_seen_year, url, description
       FROM products WHERE company_id = :id ORDER BY name',
    ['id' => $id]
);

$links = Database::all(
    'SELECT id, link_type, url, label, is_primary
       FROM links WHERE company_id = :id ORDER BY is_primary DESC, link_type, id',
    ['id' => $id]
);

$patents = Database::all(
    'SELECT patent_number, title, url, jurisdiction FROM patents WHERE company_id = :id',
    ['id' => $id]
);

$watch = Database::one(
    'SELECT w.*, u.full_name AS assigned_to FROM watches w
       LEFT JOIN users u ON u.id = w.assigned_user_id
      WHERE w.company_id = :id',
    ['id' => $id]
);

$visits = Database::all(
    'SELECT v.visit_date, v.found_change, v.significance, v.findings, u.full_name AS analyst
       FROM visits v LEFT JOIN users u ON u.id = v.user_id
      WHERE v.company_id = :id ORDER BY v.visit_date DESC, v.id DESC LIMIT 20',
    ['id' => $id]
);

$notes = Database::all(
    'SELECT n.id, n.body, n.note_date, n.is_pinned, n.created_at, u.full_name AS author
       FROM notes n LEFT JOIN users u ON u.id = n.user_id
      WHERE n.company_id = :id ORDER BY n.is_pinned DESC, n.created_at DESC LIMIT 30',
    ['id' => $id]
);

$competes = Database::all(
    'SELECT o.name AS own_product, cm.overlap, cm.threat_level, cm.their_advantage, cm.our_advantage
       FROM competition_map cm JOIN own_products o ON o.id = cm.own_product_id
      WHERE cm.company_id = :id ORDER BY o.sort_order',
    ['id' => $id]
);

$analysts = Database::all("SELECT id, full_name FROM users WHERE is_active = 1 ORDER BY full_name");

$PAGE_TITLE    = $company['name'];
$PAGE_SUBTITLE = trim(($company['country_name'] ?? '') . ($company['parent_name'] ? ' · ' . t('parent_company') . ': ' . $company['parent_name'] : ''));

$PAGE_ACTIONS = '<a class="btn" href="' . e(url('companies', 'list')) . '">' . e(t('back')) . '</a>';
if (Auth::can('analyst')) {
    $PAGE_ACTIONS .= '<a class="btn btn-primary" href="' . e(url('companies', 'form', ['id' => $id])) . '">'
                   . e(t('edit')) . '</a>';
}

require BASE_DIR . '/includes/layout/header.php';
?>

<div class="grid grid-main">
  <div>

    <!-- Facts -->
    <section class="panel">
      <div class="panel-body">
        <div class="profile-facts">
          <div>
            <div class="fact-label"><?= e(t('threat')) ?></div>
            <div class="fact-value"><?= threat_meter($company['threat_level'] === null ? null : (int) $company['threat_level']) ?></div>
          </div>
          <div>
            <div class="fact-label"><?= e(t('status')) ?></div>
            <div class="fact-value"><?= e(ucfirst((string) $company['status'])) ?></div>
          </div>
          <div>
            <div class="fact-label"><?= e(t('last_check')) ?></div>
            <div class="fact-value"><?= thermal_cell($watch['last_visit_date'] ?? null) ?></div>
          </div>
          <div>
            <div class="fact-label"><?= e(t('next_due')) ?></div>
            <div class="fact-value is-mono"><?= e(fmt_date($watch['next_due_date'] ?? null)) ?></div>
          </div>
          <div>
            <div class="fact-label"><?= e(t('website')) ?></div>
            <div class="fact-value">
              <?php if ($company['website']): ?>
                <a href="<?= e($company['website']) ?>" target="_blank" rel="noopener noreferrer">
                  <?= e(parse_url($company['website'], PHP_URL_HOST) ?: $company['website']) ?>
                </a>
              <?php else: ?>—<?php endif; ?>
            </div>
          </div>
          <?php if ($company['source_ref']): ?>
          <div>
            <div class="fact-label"><?= e(t('source_row')) ?></div>
            <div class="fact-value is-mono">#<?= e($company['source_ref']) ?></div>
          </div>
          <?php endif; ?>
        </div>

        <?php if ($company['aka'] || $company['summary']): ?>
          <div class="divider"></div>
          <?php if ($company['aka']): ?>
            <p class="small muted"><?= e(t('also_known_as')) ?>: <?= e($company['aka']) ?></p>
          <?php endif; ?>
          <?php if ($company['summary']): ?>
            <p style="margin:.4rem 0 0"><?= nl2br(e($company['summary'])) ?></p>
          <?php endif; ?>
        <?php endif; ?>

        <?php if ($tags || $rels): ?>
          <div class="divider"></div>
          <div class="chips">
            <?php foreach ($rels as $rel): ?>
              <span class="pill pill-<?= e($rel['rel_type']) ?>">
                <?= e($rel['rel_type']) ?><?= $rel['program'] ? ' · ' . e($rel['program']) : '' ?>
              </span>
            <?php endforeach; ?>
            <?php foreach ($tags as $tag):
                $label = Lang::isRtl() && $tag['name_he'] ? $tag['name_he'] : $tag['name_en']; ?>
              <a class="chip<?= $tag['is_core_competition'] ? ' is-core' : '' ?>"
                 href="<?= e(url('companies', 'list', ['tag' => $tag['slug']])) ?>">
                <span class="chip-dot" style="background:<?= e($tag['color'] ?: '#6b7c8d') ?>"></span>
                <?= e($label) ?>
              </a>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </section>

    <!-- Products -->
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('products')) ?></h2></div>
      <div class="panel-body is-flush">
        <?php if (!$products): ?>
          <p class="empty"><?= e(t('no_products')) ?></p>
        <?php else: ?>
        <div class="table-wrap">
          <table class="data">
            <thead>
              <tr>
                <th><?= e(t('product_name')) ?></th>
                <th><?= e(t('product_status')) ?></th>
                <th><?= e(t('description')) ?></th>
                <?php if (Auth::can('analyst')): ?><th></th><?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($products as $p): ?>
                <tr>
                  <td class="cell-name">
                    <?php if ($p['url']): ?>
                      <a href="<?= e($p['url']) ?>" target="_blank" rel="noopener noreferrer"><?= e($p['name']) ?></a>
                    <?php else: ?><?= e($p['name']) ?><?php endif; ?>
                  </td>
                  <td class="small"><?= e(ucfirst((string) $p['status'])) ?></td>
                  <td class="small muted"><?= e(excerpt($p['description'], 90)) ?></td>
                  <?php if (Auth::can('analyst')): ?>
                  <td class="num">
                    <form method="post" action="<?= e(url('products', 'delete')) ?>"
                          onsubmit="return confirm('<?= e(t('confirm_delete')) ?>')" style="display:inline">
                      <?= Csrf::field() ?>
                      <input type="hidden" name="id" value="<?= (int) $p['id'] ?>">
                      <input type="hidden" name="company_id" value="<?= $id ?>">
                      <button class="btn btn-sm btn-ghost btn-danger" type="submit">×</button>
                    </form>
                  </td>
                  <?php endif; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>

        <?php if (Auth::can('analyst')): ?>
        <div class="panel-body" style="border-top:1px solid var(--rule-soft)">
          <form method="post" action="<?= e(url('products', 'save')) ?>" class="inline-form">
            <?= Csrf::field() ?>
            <input type="hidden" name="company_id" value="<?= $id ?>">
            <div class="field" style="flex:2">
              <label class="label"><?= e(t('product_name')) ?></label>
              <input type="text" name="name" required maxlength="160">
            </div>
            <div class="field">
              <label class="label"><?= e(t('product_status')) ?></label>
              <select name="status">
                <?php foreach (['unknown', 'concept', 'prototype', 'production', 'discontinued'] as $s): ?>
                  <option value="<?= e($s) ?>"><?= e(ucfirst($s)) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field" style="flex:2">
              <label class="label"><?= e(t('link_url')) ?> <span class="label-note"><?= e(t('optional')) ?></span></label>
              <input type="url" name="url" maxlength="500" placeholder="https://">
            </div>
            <button class="btn" type="submit"><?= e(t('add_product')) ?></button>
          </form>
        </div>
        <?php endif; ?>
      </div>
    </section>

    <!-- Check history -->
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('check_history')) ?></h2></div>
      <div class="panel-body">
        <?php if (!$visits): ?>
          <p class="empty"><?= e(t('no_visits')) ?></p>
        <?php else: ?>
          <ul class="timeline">
            <?php foreach ($visits as $v): ?>
              <li>
                <span class="timeline-date"><?= e(fmt_date($v['visit_date'])) ?></span>
                <div>
                  <div class="timeline-body">
                    <span class="sig sig-<?= e($v['significance']) ?>" aria-hidden="true"></span>
                    <?= $v['findings'] ? nl2br(e($v['findings'])) : '<span class="muted">' . e(t('sig_none')) . '</span>' ?>
                  </div>
                  <div class="timeline-meta"><?= e($v['analyst'] ?: '—') ?> · <?= e(fmt_ago($v['visit_date'])) ?></div>
                </div>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>
    </section>

    <!-- Notes -->
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('notes')) ?></h2></div>
      <div class="panel-body">
        <?php if (!$notes): ?>
          <p class="muted small"><?= e(t('no_notes')) ?></p>
        <?php else: ?>
          <ul class="timeline">
            <?php foreach ($notes as $n): ?>
              <li>
                <span class="timeline-date"><?= e(fmt_date($n['note_date'] ?: substr((string) $n['created_at'], 0, 10))) ?></span>
                <div>
                  <div class="timeline-body"><?= nl2br(e($n['body'])) ?></div>
                  <div class="timeline-meta"><?= e($n['author'] ?: '—') ?></div>
                </div>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>

        <?php if (Auth::can('analyst')): ?>
          <div class="divider"></div>
          <form method="post" action="<?= e(url('notes', 'save')) ?>" class="stack">
            <?= Csrf::field() ?>
            <input type="hidden" name="company_id" value="<?= $id ?>">
            <div class="field">
              <label class="label" for="note-body"><?= e(t('add_note')) ?></label>
              <textarea id="note-body" name="body" rows="3" required></textarea>
            </div>
            <div><button class="btn" type="submit"><?= e(t('save')) ?></button></div>
          </form>
        <?php endif; ?>
      </div>
    </section>

  </div>

  <div>
    <!-- Watch panel: the working end of the page -->
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('log_check')) ?></h2></div>
      <div class="panel-body">
        <?php if (Auth::can('analyst')): ?>
        <form method="post" action="<?= e(url('visits', 'save')) ?>" class="stack">
          <?= Csrf::field() ?>
          <input type="hidden" name="company_id" value="<?= $id ?>">

          <div class="field">
            <label class="label" for="visit-date"><?= e(t('visit_date')) ?></label>
            <input type="date" id="visit-date" name="visit_date" value="<?= e(date('Y-m-d')) ?>" required>
          </div>

          <div class="field">
            <label class="label" for="significance"><?= e(t('significance')) ?></label>
            <select id="significance" name="significance">
              <option value="none"><?= e(t('sig_none')) ?></option>
              <option value="minor"><?= e(t('sig_minor')) ?></option>
              <option value="major"><?= e(t('sig_major')) ?></option>
            </select>
          </div>

          <div class="field">
            <label class="label" for="findings"><?= e(t('findings')) ?></label>
            <textarea id="findings" name="findings" rows="4"
                      placeholder="<?= e(t('findings_hint')) ?>"></textarea>
          </div>

          <button class="btn btn-primary" type="submit"><?= e(t('log_check')) ?></button>
        </form>
        <?php else: ?>
          <p class="muted small"><?= e(t('not_permitted')) ?></p>
        <?php endif; ?>
      </div>
    </section>

    <!-- Watch schedule -->
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('check_every')) ?></h2></div>
      <div class="panel-body stack">
        <div class="profile-facts">
          <div>
            <div class="fact-label"><?= e(t('assigned_to')) ?></div>
            <div class="fact-value"><?= e($watch['assigned_to'] ?? t('unassigned')) ?></div>
          </div>
          <div>
            <div class="fact-label"><?= e(t('check_every')) ?></div>
            <div class="fact-value is-mono">
              <?= $watch && $watch['frequency_days'] ? (int) $watch['frequency_days'] . ' ' . e(t('days')) : '—' ?>
            </div>
          </div>
        </div>

        <?php if (Auth::can('analyst')): ?>
          <div class="divider"></div>
          <form method="post" action="<?= e(url('companies', 'save')) ?>" class="stack">
            <?= Csrf::field() ?>
            <input type="hidden" name="id" value="<?= $id ?>">
            <input type="hidden" name="only_watch" value="1">

            <div class="field">
              <label class="label" for="assigned"><?= e(t('assigned_to')) ?></label>
              <select id="assigned" name="assigned_user_id">
                <option value=""><?= e(t('unassigned')) ?></option>
                <?php foreach ($analysts as $a): ?>
                  <option value="<?= (int) $a['id'] ?>"
                    <?= (int) ($watch['assigned_user_id'] ?? 0) === (int) $a['id'] ? 'selected' : '' ?>>
                    <?= e($a['full_name']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="field">
              <label class="label" for="freq"><?= e(t('check_every')) ?> (<?= e(t('days')) ?>)</label>
              <input type="number" id="freq" name="frequency_days" min="1" max="3650"
                     value="<?= e((string) ($watch['frequency_days'] ?? '')) ?>">
            </div>

            <label class="check">
              <input type="checkbox" name="is_paused" value="1" <?= !empty($watch['is_paused']) ? 'checked' : '' ?>>
              <?= e(t('paused')) ?>
            </label>

            <div><button class="btn" type="submit"><?= e(t('save')) ?></button></div>
          </form>
        <?php endif; ?>
      </div>
    </section>

    <!-- Links -->
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('links')) ?></h2></div>
      <div class="panel-body stack">
        <?php if (!$links): ?>
          <p class="muted small"><?= e(t('no_links')) ?></p>
        <?php else: ?>
          <?php foreach ($links as $l): ?>
            <div style="display:flex;gap:.5rem;align-items:baseline;justify-content:space-between">
              <div style="min-width:0">
                <span class="pill"><?= e($l['link_type']) ?></span>
                <a href="<?= e($l['url']) ?>" target="_blank" rel="noopener noreferrer" class="small">
                  <?= e($l['label'] ?: (parse_url($l['url'], PHP_URL_HOST) ?: $l['url'])) ?>
                </a>
              </div>
              <?php if (Auth::can('analyst')): ?>
                <form method="post" action="<?= e(url('links', 'delete')) ?>" style="display:inline"
                      onsubmit="return confirm('<?= e(t('confirm_delete')) ?>')">
                  <?= Csrf::field() ?>
                  <input type="hidden" name="id" value="<?= (int) $l['id'] ?>">
                  <input type="hidden" name="company_id" value="<?= $id ?>">
                  <button class="btn btn-sm btn-ghost" type="submit">×</button>
                </form>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>

        <?php if (Auth::can('analyst')): ?>
          <div class="divider"></div>
          <form method="post" action="<?= e(url('signals', 'run')) ?>">
            <?= Csrf::field() ?>
            <input type="hidden" name="company" value="<?= $id ?>">
            <button class="btn btn-sm" type="submit" data-busy="<?= e(t('crawl_running')) ?>">
              <?= e(t('crawl_check_site')) ?>
            </button>
          </form>

          <div class="divider"></div>
          <form method="post" action="<?= e(url('links', 'save')) ?>" class="stack">
            <?= Csrf::field() ?>
            <input type="hidden" name="company_id" value="<?= $id ?>">
            <div class="field">
              <label class="label"><?= e(t('link_url')) ?></label>
              <input type="url" name="url" placeholder="https://" required maxlength="700">
            </div>
            <div class="field">
              <label class="label"><?= e(t('link_type')) ?></label>
              <select name="link_type">
                <?php foreach (['website','product','news','video','blog','linkedin','patent','document','other'] as $lt): ?>
                  <option value="<?= e($lt) ?>"><?= e(ucfirst($lt)) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div><button class="btn btn-sm" type="submit"><?= e(t('add_link')) ?></button></div>
          </form>
        <?php endif; ?>
      </div>
    </section>

    <?php if ($patents): ?>
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('patents')) ?></h2></div>
      <div class="panel-body stack">
        <?php foreach ($patents as $p): ?>
          <div class="small">
            <a href="<?= e($p['url']) ?>" target="_blank" rel="noopener noreferrer" class="mono">
              <?= e($p['patent_number']) ?>
            </a>
            <?php if ($p['title']): ?><div class="muted"><?= e(excerpt($p['title'], 80)) ?></div><?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>

    <?php if ($competes): ?>
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('our_product')) ?></h2></div>
      <div class="panel-body stack">
        <?php foreach ($competes as $cm): ?>
          <div style="display:flex;justify-content:space-between;gap:.5rem;font-size:13px">
            <span><?= e($cm['own_product']) ?></span>
            <span class="pill"><?= e(t('overlap_' . $cm['overlap'])) ?></span>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>
  </div>
</div>

<?php require BASE_DIR . '/includes/layout/footer.php'; ?>
