<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Users / Invitations';

if (!gp_can_manage_project_access($pdo)) {
    http_response_code(403);
    exit('Access denied.');
}

$ok = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string)($_POST['email'] ?? ''));
    $role = trim((string)($_POST['role'] ?? 'employee'));
    $employeeId = (int)($_POST['employee_id'] ?? 0);
    $partnerId = (int)($_POST['external_partner_id'] ?? 0);
    $customerId = (int)($_POST['customer_id'] ?? 0);

    if ($email === '') $errors[] = 'Email is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email.';
    if (!in_array($role, ['admin','manager','secretary','employee','partner','customer'], true)) $errors[] = 'Invalid role.';

    if (!$errors) {
        $token = bin2hex(random_bytes(24));
        $expiresAt = date('Y-m-d H:i:s', strtotime('+7 days'));

        $stmt = $pdo->prepare("
            INSERT INTO user_invites (email, role, employee_id, external_partner_id, customer_id, invite_token, invited_by_user_id, expires_at)
            VALUES (:email, :role, :employee_id, :external_partner_id, :customer_id, :invite_token, :invited_by_user_id, :expires_at)
        ");
        $stmt->execute([
            ':email' => $email,
            ':role' => $role,
            ':employee_id' => $employeeId > 0 ? $employeeId : null,
            ':external_partner_id' => $partnerId > 0 ? $partnerId : null,
            ':customer_id' => $customerId > 0 ? $customerId : null,
            ':invite_token' => $token,
            ':invited_by_user_id' => (int)(auth_user()['id'] ?? 0),
            ':expires_at' => $expiresAt,
        ]);

        $inviteLink = '/public/auth/accept_invite.php?token=' . urlencode($token);
        $ok = 'Invite created. Link: ' . $inviteLink;
    }
}

$employees = $pdo->query("SELECT id, full_name FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();
$partners = $pdo->query("SELECT id, company_name FROM external_partners WHERE active = 1 ORDER BY company_name ASC")->fetchAll();
$customers = $pdo->query("SELECT id, name FROM customers WHERE active = 1 ORDER BY name ASC")->fetchAll();
$invites = $pdo->query("SELECT * FROM user_invites ORDER BY id DESC LIMIT 100")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo h(gp_tr($pdo, 'users_invites')); ?></h1>
    <span>Admin only</span>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

    <form method="post">
      <div class="form-grid">
        <div class="form-group"><label>Email</label><input type="email" name="email"></div>
        <div class="form-group">
          <label>Role</label>
          <select name="role">
            <option value="employee">Employee</option>
            <option value="partner">Partner</option>
            <option value="customer">Customer</option>
            <option value="secretary">Secretary</option>
            <option value="manager">Manager</option>
            <option value="admin">Admin</option>
          </select>
        </div>
        <div class="form-group">
          <label>Employee link</label>
          <select name="employee_id">
            <option value="0">-</option>
            <?php foreach ($employees as $e): ?><option value="<?php echo (int)$e['id']; ?>"><?php echo h($e['full_name']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Partner link</label>
          <select name="external_partner_id">
            <option value="0">-</option>
            <?php foreach ($partners as $p): ?><option value="<?php echo (int)$p['id']; ?>"><?php echo h($p['company_name']); ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Customer link</label>
          <select name="customer_id">
            <option value="0">-</option>
            <?php foreach ($customers as $c): ?><option value="<?php echo (int)$c['id']; ?>"><?php echo h($c['name']); ?></option><?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit"><?php echo h(gp_tr($pdo, 'send_invite')); ?></button>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Invites</h1><span>Latest 100</span></div>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th>Email</th><th>Role</th><th>Used</th><th>Expires</th><th>Token</th></tr></thead>
        <tbody>
          <?php foreach ($invites as $i): ?>
            <tr>
              <td><?php echo h($i['email']); ?></td>
              <td><?php echo h($i['role']); ?></td>
              <td><?php echo (int)$i['is_used'] === 1 ? 'Yes' : 'No'; ?></td>
              <td><?php echo h($i['expires_at']); ?></td>
              <td><?php echo h($i['invite_token']); ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
