<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin');
$db      = Database::getInstance();
$page    = 'My Companies';
$orgId   = organizationId();
$org     = $db->fetchOne("SELECT * FROM organizations WHERE id=?", [$orgId]);
$usage   = getLicenseUsage($db, $orgId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');
    $id     = postInt('id');

    if ($action === 'create') {
        $name = post('name');
        if (!$name) {
            setFlash('error', 'Company name is required.');
        } else {
            // FIX (09 Jul 2026): companies.code is NOT NULL — generate a
            // simple one from the name instead of leaving it blank.
            $autoCode = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $name), 0, 8)) ?: 'CO' . $orgId;
            $db->execute("INSERT INTO companies (organization_id,name,code) VALUES (?,?,?)", [$orgId, $name, $autoCode]);
            setFlash('success', "Company '$name' created. It shares your organization's {$usage['limit']}-user license pool with your other companies — it doesn't get a separate quota.");
        }
    } elseif ($action === 'rename') {
        $name = post('name');
        if ($name) {
            $db->execute("UPDATE companies SET name=? WHERE id=? AND organization_id=?", [$name, $id, $orgId]);
            setFlash('success', 'Company renamed.');
        }
    } elseif ($action === 'delete') {
        $inUse = (int)$db->fetchValue("SELECT COUNT(*) FROM employees WHERE company_id=?", [$id]);
        if ($inUse > 0) {
            setFlash('error', "Can't delete — this company still has $inUse employee(s) linked to it. Transfer or remove them first.");
        } else {
            $db->execute("DELETE FROM companies WHERE id=? AND organization_id=?", [$id, $orgId]);
            setFlash('success', 'Company deleted.');
        }
    }
    header('Location: ' . BASE_URL . '/modules/organization/companies.php'); exit;
}

$companies = $db->fetchAll(
    "SELECT c.*,
            (SELECT COUNT(*) FROM users u WHERE u.company_id=c.id AND u.is_active=1) AS used_users,
            (SELECT COUNT(*) FROM employees e WHERE e.company_id=c.id) AS total_employees
       FROM companies c WHERE c.organization_id=? ORDER BY c.name",
    [$orgId]
);

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3 mb-3">
  <div class="col-12">
    <div class="pc-card d-flex align-items-center justify-content-between flex-wrap gap-2">
      <div>
        <div class="pc-card-title mb-0"><i class="ti ti-buildings me-2"></i><?=clean($org['name'] ?? '')?> — Companies</div>
        <small class="text-muted">All companies below share ONE license pool. Creating another company does not give you extra user seats — it just lets you organize employees under a different company name (e.g. a subsidiary or branch).</small>
      </div>
      <div class="d-flex align-items-center gap-2" style="min-width:220px">
        <div class="pc-progress flex-fill" style="height:10px">
          <div class="pc-progress-fill" style="width:<?=$usage['limit']>0?min(100,round($usage['used']/$usage['limit']*100)):0?>%;background:<?=$usage['used']>=$usage['limit']?'var(--pc-red)':'var(--pc-green)'?>"></div>
        </div>
        <span class="fw-bold"><?=$usage['used']?>/<?=$usage['limit']?> users total</span>
      </div>
    </div>
  </div>
</div>

<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-plus me-2"></i>Add Company</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="create">
        <div class="mb-2">
          <label class="pc-label">Company Name <span class="text-danger">*</span></label>
          <input type="text" name="name" class="form-control form-control-sm" required placeholder="e.g. ABC Logistics">
        </div>
        <button class="btn btn-pc btn-sm w-100">Create Company</button>
      </form>
    </div>
  </div>

  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title">Your Companies (<?=count($companies)?>)</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Company</th><th>Employees</th><th>Active Users</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach ($companies as $c): ?>
          <tr>
            <td>
              <form method="POST" class="d-flex gap-1">
                <?=csrfField()?><input type="hidden" name="action" value="rename"><input type="hidden" name="id" value="<?=$c['id']?>">
                <input type="text" name="name" value="<?=clean($c['name'])?>" class="form-control form-control-sm">
                <button class="btn btn-xs btn-outline-primary py-0 px-2">Save</button>
              </form>
            </td>
            <td><?=$c['total_employees']?></td>
            <td><?=$c['used_users']?></td>
            <td>
              <form method="POST" onsubmit="return confirm('Delete <?=clean($c['name'])?>?')">
                <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$c['id']?>">
                <button class="btn btn-xs btn-outline-danger py-0 px-2" <?=$c['total_employees']>0?'disabled title="Has employees — transfer them first"':''?>>Delete</button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>