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

// 07 Jul 2026: license is now sold per-ORGANIZATION, not per-company. An
// organization's admin can run multiple companies under it (subsidiaries,
// branches, etc) but they all draw from the same pool of purchased seats.
// This screen now manages users across every company inside the admin's
// organization, and lets them pick which company a new user belongs to.
$orgCompanies = $db->fetchAll("SELECT id,name FROM companies WHERE organization_id=? ORDER BY name", [$orgId]);
$companyIds   = array_column($orgCompanies, 'id');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action    = post('action');
    $id        = postInt('id');
    $companyId = postInt('company_id') ?: ($companyIds[0] ?? 0);

    if ($action === 'create') {
        $username = post('username');
        $role     = post('role');
        $empId    = postInt('employee_id') ?: null;
        $pwd      = post('password') ?: 'Gmhpl_2025';

        $dup = $db->fetchOne("SELECT id FROM users WHERE username=?", [$username]);
        if ($dup) {
            setFlash('error','Username already exists.');
        } elseif (!in_array($companyId, $companyIds)) {
            setFlash('error','Invalid company selected.');
        } elseif (!hasLicenseCapacity($db, $orgId)) {
            // FIX: enforce purchased user-license cap for the whole
            // organization (summed across all its companies). If they're
            // out of seats, they must deactivate someone first (swap).
            setFlash('error', "License limit reached ({$usage['used']}/{$usage['limit']} users across all your companies). Deactivate an existing user below before adding a new one.");
        } else {
            $hash = password_hash($pwd, PASSWORD_BCRYPT, ['cost'=>12]);
            $db->execute("INSERT INTO users (employee_id,username,password_hash,role,company_id,is_active,must_change_password) VALUES (?,?,?,?,?,1,1)",
                [$empId,$username,$hash,$role,$companyId]);
            setFlash('success',"User '$username' created. Default password: $pwd");
        }
    } elseif ($action === 'edit') {
        $data = ['role'=>post('role'), 'employee_id'=>postInt('employee_id')?:null];
        if (post('new_password')) $data['password_hash'] = password_hash(post('new_password'), PASSWORD_BCRYPT, ['cost'=>12]);
        if (in_array($companyId, $companyIds)) $data['company_id'] = $companyId;
        $db->updateRow('users', $data, $id);
        setFlash('success','User updated.');
    } elseif ($action === 'toggle') {
        $target = $db->fetchOne("SELECT u.* FROM users u JOIN companies c ON c.id=u.company_id WHERE u.id=? AND c.organization_id=?", [$id, $orgId]);
        if (!$target) {
            setFlash('error', 'User not found.');
        } elseif (!$target['is_active'] && !hasLicenseCapacity($db, $orgId)) {
            // Trying to re-activate but no free seat anywhere in the
            // organization — this is the "swap" case: deactivate someone
            // else first (in any of your companies) to free a seat.
            setFlash('error', "License limit reached ({$usage['used']}/{$usage['limit']} users). Deactivate another user (in any of your companies) first to free up a seat.");
        } else {
            $db->execute("UPDATE users SET is_active=NOT is_active WHERE id=?", [$id]);
            setFlash('success','User status toggled.');
        }
    } elseif ($action === 'reset_password') {
        $hash = password_hash('Gmhpl_2025', PASSWORD_BCRYPT, ['cost'=>12]);
        $db->execute("UPDATE users u JOIN companies c ON c.id=u.company_id SET u.password_hash=?,u.must_change_password=1 WHERE u.id=? AND c.organization_id=?", [$hash,$id,$orgId]);
        setFlash('success','Password reset to Gmhpl_2025.');
    } elseif ($action === 'delete') {
        $db->execute("DELETE u FROM users u JOIN companies c ON c.id=u.company_id WHERE u.id=? AND c.organization_id=? AND u.role!='superadmin'", [$id,$orgId]);
        setFlash('success','User deleted.');
    }
    header('Location: ' . BASE_URL . '/modules/users/index.php'); exit;
}

$editId    = cleanInt($_GET['edit'] ?? 0);
$editUser  = $editId ? $db->fetchOne("SELECT u.* FROM users u JOIN companies c ON c.id=u.company_id WHERE u.id=? AND c.organization_id=?", [$editId, $orgId]) : null;
$users     = $db->fetchAll(
    "SELECT u.*, c.name AS company_name, CONCAT(e.first_name,' ',e.last_name) AS emp_name, e.employee_id AS emp_code
       FROM users u
       JOIN companies c ON c.id=u.company_id
  LEFT JOIN employees e ON e.id=u.employee_id
      WHERE c.organization_id=?
      ORDER BY c.name, u.role, u.username",
    [$orgId]
);
$employees = $db->fetchAll(
    "SELECT id,company_id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label
       FROM employees WHERE status='active' AND company_id IN (" . implode(',', array_fill(0,count($companyIds),'?')) . ")
       ORDER BY first_name",
    $companyIds ?: [0]
);
$roles     = ['superadmin'=>'Super Admin','admin'=>'Admin','hr'=>'HR','manager'=>'Manager','employee'=>'Employee'];
$usage     = getLicenseUsage($db, $orgId); // refresh after any POST redirect

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 Usage</div>
        <small class="text-muted">Shared across all <?=count($orgCompanies)?> of your companies. Deactivate someone to free a seat before adding a new user (swap).</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']?></span>
      </div>
    </div>
  </div>
</div>
<div class="row g-3">
  <!-- Create/Edit Form -->
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-user-plus me-2"></i><?=$editUser?'Edit User':'Create User'?></div>
      <form method="POST">
        <?=csrfField()?>
        <input type="hidden" name="action" value="<?=$editUser?'edit':'create'?>">
        <?php if ($editUser): ?><input type="hidden" name="id" value="<?=$editUser['id']?>"><?php endif; ?>

        <?php if (count($orgCompanies) > 1): ?>
        <div class="mb-2">
          <label class="pc-label">Company <span class="text-danger">*</span></label>
          <select name="company_id" class="form-select form-select-sm">
            <?php foreach ($orgCompanies as $c): ?>
            <option value="<?=$c['id']?>" <?=($editUser['company_id']??$companyIds[0]??0)==$c['id']?'selected':''?>><?=clean($c['name'])?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php else: ?>
        <input type="hidden" name="company_id" value="<?=$companyIds[0]??0?>">
        <?php endif; ?>

        <?php if (!$editUser): ?>
        <div class="mb-2">
          <label class="pc-label">Username <span class="text-danger">*</span></label>
          <input type="text" name="username" class="form-control form-control-sm" required placeholder="e.g. emp0001">
        </div>
        <div class="mb-2">
          <label class="pc-label">Password (leave blank for default: Gmhpl_2025)</label>
          <input type="password" name="password" class="form-control form-control-sm" placeholder="Gmhpl_2025">
        </div>
        <?php else: ?>
        <div class="mb-2">
          <label class="pc-label">Username</label>
          <input type="text" class="form-control form-control-sm" value="<?=clean($editUser['username'])?>" disabled>
        </div>
        <div class="mb-2">
          <label class="pc-label">New Password (leave blank to keep current)</label>
          <input type="password" name="new_password" class="form-control form-control-sm" placeholder="Leave blank to keep">
        </div>
        <?php endif; ?>

        <div class="mb-2">
          <label class="pc-label">Role <span class="text-danger">*</span></label>
          <select name="role" class="form-select form-select-sm">
            <?php foreach ($roles as $v=>$l): ?>
            <option value="<?=$v?>" <?=($editUser['role']??'employee')===$v?'selected':''?>><?=$l?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="mb-3">
          <label class="pc-label">Link to Employee (optional)</label>
          <select name="employee_id" class="form-select form-select-sm">
            <option value="">None (standalone user)</option>
            <?php foreach ($employees as $e): ?>
            <option value="<?=$e['id']?>" <?=($editUser['employee_id']??'')==$e['id']?'selected':''?>><?=clean($e['label'])?></option>
            <?php endforeach; ?>
          </select>
        </div>

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

  <!-- Users Table -->
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-users me-2"></i>All Users (<?=count($users)?>)</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead>
            <tr><th>Username</th><th>Company</th><th>Role</th><th>Linked Employee</th><th>Last Login</th><th>Status</th><th>Actions</th></tr>
          </thead>
          <tbody>
          <?php foreach ($users as $u): ?>
          <tr>
            <td>
              <div class="fw-semibold"><?=clean($u['username'])?></div>
              <?php if($u['must_change_password']): ?><small class="text-warning"><i class="ti ti-lock me-1"></i>Must change pwd</small><?php endif; ?>
            </td>
            <td><span class="small"><?=clean($u['company_name'])?></span></td>
            <td>
              <?php
              $roleColors = ['superadmin'=>'purple','admin'=>'brand','hr'=>'blue','manager'=>'green','employee'=>'amber'];
              $rc = $roleColors[$u['role']]??'brand';
              ?>
              <span class="badge" style="background:var(--pc-<?=$rc?>-bg,var(--pc-brand-light));color:var(--pc-<?=$rc?>,var(--pc-brand))"><?=$roles[$u['role']]??$u['role']?></span>
            </td>
            <td>
              <?php if ($u['emp_name']): ?>
              <div class="fw-semibold" style="font-size:12px"><?=clean($u['emp_name'])?></div>
              <small class="text-muted"><?=clean($u['emp_code']??'')?></small>
              <?php else: ?><span class="text-muted">—</span><?php endif; ?>
            </td>
            <td><span class="text-muted small"><?=$u['last_login']?fmtDate($u['last_login'],'d M Y H:i'):'Never'?></span></td>
            <td><?=statusBadge($u['is_active']?'active':'inactive')?></td>
            <td>
              <div class="d-flex gap-1 flex-wrap">
                <a href="?edit=<?=$u['id']?>" class="btn btn-xs btn-outline-primary py-0 px-1" title="Edit"><i class="ti ti-edit"></i></a>

                <?php if ($u['role'] !== 'superadmin'): ?>
                <form method="POST" class="d-inline">
                  <?=csrfField()?><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?=$u['id']?>">
                  <button class="btn btn-xs <?=$u['is_active']?'btn-outline-warning':'btn-outline-success'?> py-0 px-1" title="<?=$u['is_active']?'Deactivate':'Activate'?>">
                    <i class="ti <?=$u['is_active']?'ti-user-off':'ti-user-check'?>"></i>
                  </button>
                </form>
                <form method="POST" class="d-inline">
                  <?=csrfField()?><input type="hidden" name="action" value="reset_password"><input type="hidden" name="id" value="<?=$u['id']?>">
                  <button class="btn btn-xs btn-outline-secondary py-0 px-1" title="Reset to Gmhpl_2025"><i class="ti ti-key"></i></button>
                </form>
                <form method="POST" class="d-inline" onsubmit="return confirm('Delete user <?=clean($u['username'])?>?')">
                  <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$u['id']?>">
                  <button class="btn btn-xs btn-outline-danger py-0 px-1" title="Delete"><i class="ti ti-trash"></i></button>
                </form>
                <?php endif; ?>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>