<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Portal Invite';

$type = trim((string)($_GET['type'] ?? $_POST['type'] ?? 'employee'));
$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if (!in_array($type, ['employee', 'partner', 'customer'], true) || $id <= 0) die('Missing or invalid portal target.');

if ($type === 'employee') {
    $stmt = $pdo->prepare("SELECT * FROM employees WHERE id = :id LIMIT 1");
} elseif ($type === 'partner') {
    $stmt = $pdo->prepare("SELECT * FROM external_partners WHERE id = :id LIMIT 1");
} else {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = :id LIMIT 1");
}
$stmt->execute([':id' => $id]);
$item = $stmt->fetch();
if (!$item) die('Target not found.');

if ($type === 'employee') {
    $email = (string)($item['email'] ?? '');
    $name = (string)($item['full_name'] ?? '');
} elseif ($type === 'partner') {
    $email = (string)($item['email'] ?? '');
    $name = trim((string)($item['company_name'] ?? '') . ' ' . (string)($item['contact_person'] ?? ''));
} else {
    $email = (string)($item['email'] ?? '');
    $name = (string)($item['name'] ?? '');
}

$token = bin2hex(random_bytes(24));
$expires = date('Y-m-d H:i:s', strtotime('+48 hours'));
$whereField = $type === 'employee' ? 'employee_id' : ($type === 'partner' ? 'external_partner_id' : 'customer_id');

$stmt = $pdo->prepare("SELECT id FROM users WHERE {$whereField} = :target_id LIMIT 1");
$stmt->execute([':target_id' => $id]);
$userId = (int)$stmt->fetchColumn();

if ($userId > 0) {
    $stmt = $pdo->prepare("UPDATE users SET reset_token = :token, reset_token_expires_at = :expires, email = COALESCE(NULLIF(:email,''), email), is_active = 1 WHERE id = :id");
    $stmt->execute([':token'=>$token, ':expires'=>$expires, ':email'=>$email, ':id'=>$userId]);
} else {
    $username = preg_replace('/[^a-z0-9._-]/i', '', strtolower(str_replace(' ', '.', $name)));
    if ($username === '') $username = $type . '.' . $id;
    $baseUsername = $username;
    $n = 1;
    while (true) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :u");
        $stmt->execute([':u' => $username]);
        if ((int)$stmt->fetchColumn() === 0) break;
        $username = $baseUsername . '.' . $n;
        $n++;
    }
    $stmt = $pdo->prepare("INSERT INTO users (username,email,password_hash,role,employee_id,external_partner_id,customer_id,is_active,reset_token,reset_token_expires_at) VALUES (:username,:email,:password_hash,:role,:employee_id,:external_partner_id,:customer_id,1,:token,:expires)");
    $stmt->execute([
        ':username'=>$username, ':email'=>$email!==''?$email:null, ':password_hash'=>password_hash(bin2hex(random_bytes(12)), PASSWORD_DEFAULT),
        ':role'=>$type, ':employee_id'=>$type==='employee'?$id:null, ':external_partner_id'=>$type==='partner'?$id:null,
        ':customer_id'=>$type==='customer'?$id:null, ':token'=>$token, ':expires'=>$expires
    ]);
}
$setupLink = '/public/auth/create_password.php?token=' . urlencode($token);

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header"><div class="page-header-title"><h1>Portal invite created</h1><span><?php echo h($name); ?></span></div></div>
<div class="card">
  <p><strong>Type:</strong> <?php echo h($type); ?></p>
  <p><strong>Email:</strong> <?php echo h($email); ?></p>
  <p><strong>Setup link:</strong></p>
  <p><a href="<?php echo h($setupLink); ?>" target="_blank" rel="noopener"><?php echo h($setupLink); ?></a></p>
  <p class="small">Send this link to the user so they can create their own password. Link validity: 48 hours.</p>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
