<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/rbac.php";
require_once "../includes/lang.php";
require_once "../includes/csrf.php";

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
$isAgency = ($roleId === 3);
$canManageUsers = hasPermission("manage_users");

if (!$canManageUsers && !$isAgency) {
    http_response_code(403);
    echo "Forbidden";
    exit;
}
$csrf = csrfToken();
?>
<!DOCTYPE HTML>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars(t("add_account")) ?> - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<link rel="stylesheet" href="assets/css/dashboard.css" type="text/css">
<link rel="stylesheet" href="assets/css/owl.carousel.min.css" type="text/css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div class="dashboard_container">
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<div class="logo"><a href="<?= $isAgency ? 'agency_dashboard.php' : 'admin.php' ?>"><img src="assets/images/logo.png" alt="logo"/></a></div>
<div id="dashboard-responsive-nav-trigger"><i class="fa fa-reorder"></i></div>
</div>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li><a href="<?= $isAgency ? 'agency_dashboard.php' : 'admin.php' ?>"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li class="active"><a href="nalog.php"><i class="fa fa-plus"></i> <?= htmlspecialchars(t("add_account")) ?></a></li>
<li><a href="logout.php"><i class="fa fa-power-off"></i> <?= htmlspecialchars(t("logout")) ?></a></li>
</ul>
</div>

<div class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2><?= htmlspecialchars(t("add_account")) ?></h2></div></div></div>
<div class="row">
<div class="col-lg-12 col-md-12">
<form id="createUserForm" enctype="multipart/form-data">
<input type="hidden" id="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
<div class="add_listing_info">
<h3><?= htmlspecialchars(t("basic_information")) ?></h3>
<div class="form-group"><label class="label-title"><?= htmlspecialchars(t("first_name")) ?></label><input type="text" id="first_name" class="form-control"></div>
<div class="form-group"><label class="label-title"><?= htmlspecialchars(t("last_name")) ?></label><input type="text" id="last_name" class="form-control"></div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("role")) ?></label>
<select id="role_id" class="form-control">
<?php if ($isAgency): ?>
<option value="2" selected>worker</option>
<?php else: ?>
<option value="2">worker</option>
<option value="3">agency</option>
<option value="4">company</option>
<option value="5">moderator</option>
<option value="1">admin</option>
<?php endif; ?>
</select>
</div>
<div class="form-group role-only role-agency">
<label class="label-title"><?= htmlspecialchars(t("partner_agency")) ?></label>
<div>
  <label style="font-weight:normal;">
    <input type="checkbox" id="is_partner_agency" value="1"> <?= htmlspecialchars(t("is_partner")) ?>
  </label>
</div>
</div>
<div class="form-group"><label class="label-title">Email</label><input type="email" id="email" class="form-control"></div>
<div class="form-group"><label class="label-title">Password</label><input type="password" id="password" class="form-control"></div>
<p id="workerOptionalMsg" class="role-only role-worker" style="display:none;color:#777;margin-top:-6px;">For worker creation, email and password are optional.</p>
<div class="form-group role-only role-worker">
<label class="label-title"><?= htmlspecialchars(t("skills")) ?></label>
<div id="skillsCheckboxList" class="row"></div>
</div>
<div class="form-group role-only role-worker role-agency role-company"><label class="label-title"><?= htmlspecialchars(t("location")) ?></label><input type="text" id="location" class="form-control"></div>
<div class="form-group role-only role-worker">
<label class="label-title">Languages</label>
<input type="text" id="languages" class="form-control">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Country</label>
<input type="text" id="country" class="form-control">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Availability</label>
<input type="date" id="availability" class="form-control">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Position <span style="color:#c00">*</span></label>
<select id="position" class="form-control" required>
  <option value="">Select position</option>
</select>
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Photo URL</label>
<input type="url" id="photo_url" class="form-control" placeholder="https://example.com/photo.jpg" pattern="https?://.*" inputmode="url">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">YouTube URL</label>
<input type="url" id="youtube_url" class="form-control" placeholder="https://www.youtube.com/watch?v=..." pattern="https?://.*" inputmode="url">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Desired salary (from)</label>
<input type="number" min="0" id="desired_salary_from" class="form-control" placeholder="500">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Desired salary (to)</label>
<input type="number" min="0" id="desired_salary_to" class="form-control" placeholder="1500">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Video interview (YouTube link)</label>
<input type="url" id="video_interview" class="form-control" placeholder="https://www.youtube.com/watch?v=..." pattern="https?://.*" inputmode="url">
</div>
<div class="form-group role-only role-worker">
<label class="label-title">Video work (YouTube link)</label>
<input type="url" id="video_work" class="form-control" placeholder="https://www.youtube.com/watch?v=..." pattern="https?://.*" inputmode="url">
</div>
<div class="form-group role-only role-company"><label class="label-title">PIB</label><input type="text" id="company_tax_id" class="form-control"></div>
<div class="form-group role-only role-company"><label class="label-title">Address</label><input type="text" id="company_address" class="form-control"></div>
<div class="form-group role-only role-company">
<label class="label-title">Company package</label>
<select id="company_plan_code" class="form-control">
<option value="">Select package</option>
<option value="COMPANY_BASIC">7-day package</option>
<option value="COMPANY_PRO">15-day package</option>
<option value="COMPANY_ENTERPRISE">30-day package</option>
</select>
</div>
<div class="form-group role-only role-agency"><label class="label-title">PIB</label><input type="text" id="agency_tax_id" class="form-control"></div>
<div class="form-group role-only role-agency"><label class="label-title">Address</label><input type="text" id="agency_address" class="form-control"></div>
<div class="form-group role-only role-worker role-agency role-company"><label class="label-title"><?= htmlspecialchars(t("bio")) ?></label><textarea id="bio" class="form-control"></textarea></div>
</div>
<div class="add_listing_info">
<input type="submit" value="<?= htmlspecialchars(t("save")) ?>" class="btn">
<span id="createMsg" style="margin-left:10px;"></span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>

<script>
async function loadSkillCheckboxes() {
  const wrap = document.getElementById("skillsCheckboxList");
  wrap.innerHTML = "";
  const r = await fetch("../api/skills.php", { credentials: "same-origin" });
  const j = await r.json().catch(() => ({ success: false, data: [] }));
  if (!j.success || !Array.isArray(j.data)) {
    wrap.innerHTML = "<div class='col-md-12'>Unable to load skills.</div>";
    return;
  }
  j.data.forEach(s => {
    const col = document.createElement("div");
    col.className = "col-md-4";
    col.innerHTML = '<label style="font-weight:normal;"><input type="checkbox" value="' + parseInt(s.id,10) + '"> ' + (s.name || '') + '</label>';
    wrap.appendChild(col);
  });
}

function applyRoleFieldsVisibility() {
  const roleId = parseInt(document.getElementById("role_id").value, 10) || 0;
  const all = document.querySelectorAll(".role-only");
  all.forEach(el => {
    el.style.display = "none";
  });

  if (roleId === 2) {
    document.querySelectorAll(".role-worker").forEach(el => el.style.display = "");
  } else if (roleId === 3) {
    document.querySelectorAll(".role-agency").forEach(el => el.style.display = "");
  } else if (roleId === 4) {
    document.querySelectorAll(".role-company").forEach(el => el.style.display = "");
  }
}

document.getElementById("createUserForm").addEventListener("submit", async function(e){
  e.preventDefault();
  const fd = new FormData();
  fd.append("csrf_token", document.getElementById("csrf_token").value);
  fd.append("first_name", document.getElementById("first_name").value.trim());
  fd.append("last_name", document.getElementById("last_name").value.trim());
  fd.append("role_id", String(parseInt(document.getElementById("role_id").value, 10) || 0));
  fd.append("email", document.getElementById("email").value.trim());
  fd.append("password", document.getElementById("password").value.trim());
  fd.append("location", document.getElementById("location").value.trim());
  fd.append("bio", document.getElementById("bio").value.trim());
  fd.append("is_partner_agency", document.getElementById("is_partner_agency") ? (document.getElementById("is_partner_agency").checked ? "1" : "0") : "0");
  fd.append("company_tax_id", document.getElementById("company_tax_id") ? document.getElementById("company_tax_id").value.trim() : "");
  fd.append("company_address", document.getElementById("company_address") ? document.getElementById("company_address").value.trim() : "");
  fd.append("agency_tax_id", document.getElementById("agency_tax_id") ? document.getElementById("agency_tax_id").value.trim() : "");
  fd.append("agency_address", document.getElementById("agency_address") ? document.getElementById("agency_address").value.trim() : "");
  fd.append("company_plan_code", document.getElementById("company_plan_code") ? document.getElementById("company_plan_code").value : "");
  fd.append("languages", document.getElementById("languages") ? document.getElementById("languages").value.trim() : "");
  fd.append("country", document.getElementById("country") ? document.getElementById("country").value.trim() : "");
  fd.append("availability", document.getElementById("availability") ? document.getElementById("availability").value.trim() : "");
  fd.append("certificates", "");
  fd.append("position", document.getElementById("position") ? document.getElementById("position").value.trim() : "");
  fd.append("cv_url", "");
  fd.append("photo_url", document.getElementById("photo_url") ? document.getElementById("photo_url").value.trim() : "");
  fd.append("youtube_url", document.getElementById("youtube_url") ? document.getElementById("youtube_url").value.trim() : "");
  fd.append("desired_salary_from", document.getElementById("desired_salary_from") ? document.getElementById("desired_salary_from").value.trim() : "");
  fd.append("desired_salary_to", document.getElementById("desired_salary_to") ? document.getElementById("desired_salary_to").value.trim() : "");

  const skillIds = Array.from(document.querySelectorAll('#skillsCheckboxList input[type="checkbox"]:checked')).map(cb => parseInt(cb.value, 10)).filter(v => v > 0);
  fd.append("skill_ids", JSON.stringify(skillIds));

  const vi = document.getElementById("video_interview");
  const vw = document.getElementById("video_work");
  fd.append("video_interview", vi ? (vi.value || "").trim() : "");
  fd.append("video_work", vw ? (vw.value || "").trim() : "");

  const r = await fetch("../api/users.php", {
    method: "POST",
    body: fd
  });
  const j = await r.json().catch(() => ({success:false,error:"Invalid response"}));
  const msg = document.getElementById("createMsg");
  if (j.success) {
    msg.style.color = "green";
    msg.textContent = "Created";
    this.reset();
  } else {
    msg.style.color = "red";
    msg.textContent = [j.error, j.details].filter(Boolean).join(": ") || "Error";
    console.error("Create user error:", j);
  }
});
document.getElementById("role_id").addEventListener("change", applyRoleFieldsVisibility);

async function loadPositions() {
  const sel = document.getElementById("position");
  if (!sel) return;
  const r = await fetch("../api/positions.php", { credentials: "same-origin" });
  const j = await r.json().catch(() => ({ success:false, data:[] }));
  if (!j.success || !Array.isArray(j.data)) return;
  j.data.filter(p => parseInt(p.is_active,10) === 1).forEach(p => {
    const op = document.createElement("option");
    op.value = (p.name || "").trim();
    op.textContent = (p.name || "").trim();
    sel.appendChild(op);
  });
}

if (<?php echo $isAgency ? 'true' : 'false'; ?>) {
  const roleSelect = document.getElementById("role_id");
  roleSelect.value = "2";
  roleSelect.setAttribute("disabled", "disabled");
}

loadSkillCheckboxes();
loadPositions();
applyRoleFieldsVisibility();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/owl.carousel.min.js"></script>
<script src="assets/js/interface.js"></script>
</body>
</html>
