<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin');
$db   = Database::getInstance();
$page = 'Company Management';

// FIX (07 Jul 2026): this screen used to let ANY organization's own
// admin edit their own license seat count directly (license_seats) and
// even see/edit/delete every OTHER organization's companies (no org
// scoping at all). Per the owner's explicit instruction: only the
// vendor sets/edits license counts (Organizations & Licenses screen) —
// an organization's own admin can see their license usage here but
// cannot change it. This screen is now for legal/statutory company
// details only (PAN, TAN, GST, address, etc.), scoped to the current org.
$orgCompanies = orgCompanyIds($db);
$orgId        = organizationId();

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

    // Every write below is restricted to companies inside the current org.
    if ($id && !in_array($id, $orgCompanies)) {
        setFlash('error', 'Company not found.');
        header('Location: ' . BASE_URL . '/modules/company/index.php'); exit;
    }

    if ($action === 'save') {
        $data = [
            'name'        => post('name'),
            'code'        => strtoupper(post('code')),
            'address'     => post('address'),
            'city'        => post('city'),
            'state'       => post('state'),
            'pincode'     => post('pincode'),
            'phone'       => post('phone'),
            'email'       => post('email'),
            'website'     => post('website'),
            'pan'         => strtoupper(post('pan')),
            'tan'         => strtoupper(post('tan')),
            'gst'         => strtoupper(post('gst')),
            'pf_number'   => post('pf_number'),
            'esic_number' => post('esic_number'),
        ];
        if ($id) {
            $db->updateRow('companies', $data, $id);
            setFlash('success', 'Company details updated successfully.');
        } else {
            // New companies within this org still share the org's one
            // license pool — no license_seats field here at all.
            $data['organization_id'] = $orgId;
            $newId = $db->insertRow('companies', $data);
            $db->execute("INSERT IGNORE INTO permission_policy (company_id,max_hours_per_month) VALUES (?,4.0)", [$newId]);
            setFlash('success', 'Company created successfully.');
        }
    } elseif ($action === 'delete') {
        $empCount = $db->fetchOne("SELECT COUNT(*) AS c FROM employees WHERE company_id=?", [$id]);
        if ($empCount['c'] > 0) {
            setFlash('error', 'Cannot delete company with existing employees.');
        } else {
            $db->execute("DELETE FROM companies WHERE id=?", [$id]);
            setFlash('success', 'Company deleted.');
        }
    }
    header('Location: ' . BASE_URL . '/modules/company/index.php'); exit;
}

$editId    = cleanInt($_GET['edit'] ?? 0);
$edit      = ($editId && in_array($editId, $orgCompanies)) ? $db->fetchOne("SELECT * FROM companies WHERE id=?", [$editId]) : null;
$companies = $orgCompanies ? $db->fetchAll(
    "SELECT c.*,
            (SELECT COUNT(*) FROM employees WHERE company_id=c.id) AS emp_count,
            (SELECT COUNT(*) FROM employees WHERE company_id=c.id AND status='active') AS active_count
       FROM companies c WHERE c.id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")
       ORDER BY c.name", $orgCompanies
) : [];
$orgUsage = getLicenseUsage($db, $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-id-badge-2 me-2"></i>License (view only)</div>
        <small class="text-muted">Set by your provider. To change your license count, contact them — it can't be edited here.</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:<?=$orgUsage['limit']>0?min(100,round($orgUsage['used']/$orgUsage['limit']*100)):0?>%;background:<?=$orgUsage['used']>=$orgUsage['limit']?'var(--pc-red)':'var(--pc-green)'?>"></div>
        </div>
        <span class="fw-bold"><?=$orgUsage['used']?>/<?=$orgUsage['limit']?></span>
      </div>
    </div>
  </div>
</div>
<div class="row g-3">
  <!-- Form -->
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-building me-2"></i><?=$edit ? 'Edit' : 'Add New'?> Company</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save">
        <?php if ($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>

        <div class="pc-section-divider">Basic Details</div>
        <div class="row g-2">
          <div class="col-md-8">
            <label class="pc-label">Company Name <span class="text-danger">*</span></label>
            <input type="text" name="name" class="form-control form-control-sm" value="<?=clean($edit['name']??'')?>" required>
          </div>
          <div class="col-md-4">
            <label class="pc-label">Company Code <span class="text-danger">*</span></label>
            <input type="text" name="code" class="form-control form-control-sm" style="text-transform:uppercase" value="<?=clean($edit['code']??'')?>" required placeholder="GMHPL">
          </div>
          <div class="col-12">
            <label class="pc-label">Address</label>
            <textarea name="address" class="form-control form-control-sm" rows="2"><?=clean($edit['address']??'')?></textarea>
          </div>
          <div class="col-md-4"><label class="pc-label">City</label><input type="text" name="city" class="form-control form-control-sm" value="<?=clean($edit['city']??'')?>"></div>
          <div class="col-md-4"><label class="pc-label">State</label><input type="text" name="state" class="form-control form-control-sm" value="<?=clean($edit['state']??'')?>"></div>
          <div class="col-md-4"><label class="pc-label">Pincode</label><input type="text" name="pincode" class="form-control form-control-sm" value="<?=clean($edit['pincode']??'')?>"></div>
        </div>

        <div class="pc-section-divider">Contact</div>
        <div class="row g-2">
          <div class="col-md-6"><label class="pc-label">Phone</label><input type="text" name="phone" class="form-control form-control-sm" value="<?=clean($edit['phone']??'')?>"></div>
          <div class="col-md-6"><label class="pc-label">Email</label><input type="email" name="email" class="form-control form-control-sm" value="<?=clean($edit['email']??'')?>"></div>
          <div class="col-12"><label class="pc-label">Website</label><input type="text" name="website" class="form-control form-control-sm" value="<?=clean($edit['website']??'')?>" placeholder="https://"></div>
        </div>

        <div class="pc-section-divider">Statutory Numbers</div>
        <div class="row g-2">
          <div class="col-md-6"><label class="pc-label">PAN</label><input type="text" name="pan" class="form-control form-control-sm" style="text-transform:uppercase" value="<?=clean($edit['pan']??'')?>"></div>
          <div class="col-md-6"><label class="pc-label">TAN</label><input type="text" name="tan" class="form-control form-control-sm" style="text-transform:uppercase" value="<?=clean($edit['tan']??'')?>"></div>
          <div class="col-md-6"><label class="pc-label">GSTIN</label><input type="text" name="gst" class="form-control form-control-sm" style="text-transform:uppercase" value="<?=clean($edit['gst']??'')?>"></div>
          <div class="col-md-6"><label class="pc-label">PF Number</label><input type="text" name="pf_number" class="form-control form-control-sm" value="<?=clean($edit['pf_number']??'')?>"></div>
          <div class="col-md-6"><label class="pc-label">ESIC Number</label><input type="text" name="esic_number" class="form-control form-control-sm" value="<?=clean($edit['esic_number']??'')?>"></div>
        </div>

        <div class="mt-3 d-flex gap-2">
          <button class="btn btn-pc flex-fill"><i class="ti ti-device-floppy me-1"></i><?=$edit?'Update':'Create'?> Company</button>
          <?php if ($edit): ?><a href="?" class="btn btn-outline-secondary">Cancel</a><?php endif; ?>
        </div>
      </form>
    </div>
  </div>

  <!-- Company List -->
  <div class="col-md-7">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-buildings me-2"></i>Your Companies (<?=count($companies)?>)</div>
      <?php foreach ($companies as $c): ?>
      <div class="border rounded p-3 mb-2">
        <div class="d-flex justify-content-between align-items-start">
          <div>
            <div class="fw-bold"><?=clean($c['name'])?> <code class="ms-1" style="font-size:11px"><?=clean($c['code']??'')?></code></div>
            <div class="small text-muted"><?=clean($c['city']??'')?><?=($c['state']??'')?', '.clean($c['state']):''?></div>
            <div class="small text-muted"><?=clean($c['email']??'')?> <?=clean($c['phone']??'')?></div>
            <div class="d-flex gap-2 mt-1" style="font-size:11px">
              <?php if($c['pan']??false): ?><span>PAN: <strong><?=clean($c['pan'])?></strong></span><?php endif; ?>
              <?php if($c['pf_number']??false): ?><span>PF: <strong><?=clean($c['pf_number'])?></strong></span><?php endif; ?>
            </div>
          </div>
          <div class="text-end">
            <div class="small text-muted mt-1"><?=$c['active_count']?> active user(s)</div>
          </div>
        </div>
        <div class="mt-2 d-flex gap-1">
          <a href="?edit=<?=$c['id']?>" class="btn btn-xs btn-outline-primary py-0 px-2">Edit</a>
          <a href="<?=BASE_URL?>/modules/company/policy.php?company=<?=$c['id']?>" class="btn btn-xs btn-outline-secondary py-0 px-2">Policy</a>
          <?php if($c['emp_count']==0 && count($companies) > 1): ?>
          <form method="POST" class="d-inline" onsubmit="return confirm('Delete company?')">
            <?=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">Delete</button>
          </form>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
      <?php if (!$companies): ?><div class="text-muted text-center py-4">No companies yet. Create your first company.</div><?php endif; ?>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>