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

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user["id"] ?? 0));

$isWorker = ($roleId === 2);
$isAgency = ($roleId === 3);
$isCompany = ($roleId === 4);
?>
<!DOCTYPE HTML>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars(t("my_profile")) ?> - 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">
<link rel="shortcut icon" href="assets/images/favicon-icon/favicon.png">
</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="dashboard.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 class="collapse navbar-collapse" id="navigation">
<div class="user_nav">
<div class="dropdown">
<span id="dLabel" data-toggle="dropdown"><img id="navAvatar" src="<?= htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="img" onerror="this.onerror=null;this.src='assets/images/100x100.jpg';"></span>
<ul class="dropdown-menu" aria-labelledby="dLabel">
<li><a href="dashboard.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li class="active"><a href="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a></li>
<li><a href="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="agencies.php"><i class="fa fa-building"></i> Agencies</a></li>
<li><a href="companies.php"><i class="fa fa-briefcase"></i> Companies</a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Match History</a></li>
<li><a href="chat.php"><i class="fa fa-comments"></i> <?= htmlspecialchars(t("support")) ?></a></li>
<li><a href="logout.php"><i class="fa fa-power-off"></i> <?= htmlspecialchars(t("logout")) ?></a></li>
</ul>
</div>
</div>
</div>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li><a href="dashboard.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li class="active"><a href="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a></li>
<li><a href="workers.php"><i class="fa fa-users"></i> Workers</a></li>
<li><a href="agencies.php"><i class="fa fa-building"></i> Agencies</a></li>
<li><a href="companies.php"><i class="fa fa-briefcase"></i> Companies</a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Match History</a></li>
<li><a href="chat.php"><i class="fa fa-comments"></i> <?= htmlspecialchars(t("support")) ?></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("my_profile")) ?></h2></div></div></div>

<div class="row">
<div class="col-lg-12 col-md-12">
<form id="profileForm">
<input type="hidden" id="csrf_token" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">

<?php if ($isWorker): ?>
<div class="dashboard-list-box">
<h4>Worker Profile</h4>
<div class="padding-20">
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("skills")) ?></label>
<div id="skillsCheckboxes"></div>
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("languages")) ?></label>
<input type="text" id="languages" class="form-control" placeholder="English, Srpski, German">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("country")) ?></label>
<input type="text" id="country" class="form-control" placeholder="Serbia">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("availability")) ?></label>
<input type="date" id="availability" class="form-control">
</div>
<div class="form-group">
<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">
<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">
<label class="label-title"><?= htmlspecialchars(t("certificates")) ?></label>
<textarea id="certificates" class="form-control"></textarea>
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("cv_url")) ?></label>
<input type="url" id="cv_url" class="form-control" placeholder="https://example.com/cv.pdf">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("location")) ?></label>
<input type="text" id="location" class="form-control" placeholder="Belgrade, Serbia">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("bio")) ?></label>
<textarea id="bio" class="form-control" rows="5"></textarea>
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("photo_url")) ?></label>
<input type="url" id="photo_url" class="form-control" placeholder="https://...">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("youtube_url")) ?></label>
<input type="url" id="youtube_url" class="form-control" placeholder="https://youtube.com/watch?v=...">
</div>
<div id="youtubeEmbedBox" style="margin-top:15px;"></div>
</div>
</div>
<?php endif; ?>

<?php if ($isAgency): ?>
<div class="dashboard-list-box">
<h4>Agency Profile</h4>
<div class="padding-20">
<div class="form-group">
<label class="label-title">Agency Name</label>
<input type="text" id="agency_name" class="form-control" placeholder="Agency name">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("country")) ?></label>
<input type="text" id="country" class="form-control" placeholder="Agency country">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("location")) ?></label>
<input type="text" id="location" class="form-control" placeholder="Agency location">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("languages")) ?></label>
<input type="text" id="languages" class="form-control" placeholder="Agency languages">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("bio")) ?></label>
<textarea id="bio" class="form-control" rows="5" placeholder="Agency description"></textarea>
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("photo_url")) ?></label>
<input type="url" id="photo_url" class="form-control" placeholder="Agency logo/photo URL">
</div>
</div>
</div>
<?php endif; ?>

<?php if ($isCompany): ?>
<div class="dashboard-list-box">
<h4>Company Profile</h4>
<div class="padding-20">
<div class="form-group">
<label class="label-title">Company Name</label>
<input type="text" id="company_name" class="form-control" placeholder="Company name">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("country")) ?></label>
<input type="text" id="country" class="form-control" placeholder="Company country">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("location")) ?></label>
<input type="text" id="location" class="form-control" placeholder="Company address/location">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("languages")) ?></label>
<input type="text" id="languages" class="form-control" placeholder="Preferred communication languages">
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("bio")) ?></label>
<textarea id="bio" class="form-control" rows="5" placeholder="Company description"></textarea>
</div>
<div class="form-group">
<label class="label-title"><?= htmlspecialchars(t("photo_url")) ?></label>
<input type="url" id="photo_url" class="form-control" placeholder="Company logo/photo URL">
</div>
</div>
</div>
<?php endif; ?>

<div class="add_listing_info">
<input type="submit" value="<?= htmlspecialchars(t("save")) ?>" class="btn">
<span id="profileMsg" style="margin-left:10px;"></span>
</div>
</form>

<div class="dashboard-list-box" style="margin-top:20px;">
<h4>Change Password</h4>
<div class="padding-20">
<form id="passwordChangeForm">
<div class="form-group">
<label class="label-title">Current Password</label>
<input type="password" id="current_password" class="form-control" required>
</div>
<div class="form-group">
<label class="label-title">New Password</label>
<input type="password" id="new_password" class="form-control" required>
</div>
<div class="form-group">
<label class="label-title">Confirm New Password</label>
<input type="password" id="confirm_password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Update Password</button>
<span id="passwordMsg" style="margin-left:10px;"></span>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

<script>
window.APP = {
  csrf: document.getElementById("csrf_token").value,
  roleId: <?= $roleId ?>
};

function ytEmbed(url) {
  if (!url) return "";
  var m = url.match(/(?:v=|youtu\.be\/)([a-zA-Z0-9_-]{6,})/);
  if (!m) return "";
  return "https://www.youtube.com/embed/" + m[1];
}

function getSelectedSkillIds() {
  return Array.from(document.querySelectorAll('#skillsCheckboxes input[type="checkbox"]:checked'))
    .map(function(cb){ return parseInt(cb.value, 10); })
    .filter(function(v){ return Number.isInteger(v) && v > 0; });
}

function fieldValue(id) {
  var el = document.getElementById(id);
  return el ? String(el.value || "").trim() : "";
}

async function loadSkillsCheckboxes(selectedCsv) {
  if (window.APP.roleId !== 2) return;
  var wrap = document.getElementById("skillsCheckboxes");
  if (!wrap) return;

  var selectedSet = new Set(
    String(selectedCsv || "")
      .split(",")
      .map(function(v){ return parseInt(String(v).trim(), 10); })
      .filter(function(v){ return Number.isInteger(v) && v > 0; })
  );

  var r = await fetch("../api/skills.php", { credentials: "same-origin" });
  var j = await r.json().catch(function(){ return { success:false, data:[] }; });

  wrap.innerHTML = "";
  if (!j.success || !Array.isArray(j.data)) return;

  j.data.forEach(function(s){
    var id = parseInt(s.id, 10);
    var name = s.name || ("Skill #" + id);
    var row = document.createElement("label");
    row.style.display = "block";
    row.style.marginBottom = "6px";
    row.innerHTML = '<input type="checkbox" value="' + id + '"' + (selectedSet.has(id) ? " checked" : "") + '> ' + name;
    wrap.appendChild(row);
  });
}

async function loadProfile() {
  var r = await fetch("../api/profile_update.php?user_id=self", { credentials: "same-origin" });
  var j = await r.json().catch(function(){ return { status:"error", message:"invalid_response", data:{} }; });
  if (j.status !== "success" || !j.data) return;

  ["agency_name","company_name","languages","country","availability","certificates","cv_url","location","bio","photo_url","youtube_url","desired_salary_from","desired_salary_to"].forEach(function(id){
    var el = document.getElementById(id);
    if (el) el.value = j.data[id] || "";
  });

  await loadSkillsCheckboxes(j.data.skills || "");

  if (window.APP.roleId === 2) {
    renderYouTube();
  }
}

function renderYouTube() {
  if (window.APP.roleId !== 2) return;
  var box = document.getElementById("youtubeEmbedBox");
  if (!box) return;
  var url = fieldValue("youtube_url");
  var embed = ytEmbed(url);
  box.innerHTML = embed
    ? '<iframe width="420" height="236" src="' + embed + '" frameborder="0" allowfullscreen></iframe>'
    : "";
}

document.getElementById("profileForm").addEventListener("submit", async function(e){
  e.preventDefault();

  var payload = {
    csrf: window.APP.csrf,
    languages: fieldValue("languages"),
    country: fieldValue("country"),
    location: fieldValue("location"),
    bio: fieldValue("bio"),
    photo_url: fieldValue("photo_url")
  };

  if (window.APP.roleId === 3) {
    payload.agency_name = fieldValue("agency_name");
  } else if (window.APP.roleId === 4) {
    payload.company_name = fieldValue("company_name");
  } else if (window.APP.roleId === 2) {
    payload.skills = getSelectedSkillIds().join(",");
    payload.availability = fieldValue("availability");
    payload.certificates = fieldValue("certificates");
    payload.cv_url = fieldValue("cv_url");
    payload.youtube_url = fieldValue("youtube_url");
    payload.desired_salary_from = fieldValue("desired_salary_from");
    payload.desired_salary_to = fieldValue("desired_salary_to");
  }

  var msg = document.getElementById("profileMsg");
  try {
    var r = await fetch("../api/profile_update.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify(payload)
    });
    var raw = await r.text();
    var j;
    try {
      j = JSON.parse(raw);
    } catch (e) {
      j = { status:"error", message:"invalid_response" };
    }

    if (j.status === "success") {
      msg.style.color = "green";
      msg.textContent = "Profile saved successfully";
      renderYouTube();
    } else {
      msg.style.color = "red";
      msg.textContent = j.message || "Validation failed";
    }
  } catch (e) {
    msg.style.color = "red";
    msg.textContent = "Request failed";
  }
});

var ytInput = document.getElementById("youtube_url");
if (ytInput) ytInput.addEventListener("input", renderYouTube);

document.getElementById("passwordChangeForm").addEventListener("submit", async function(e) {
  e.preventDefault();
  var msg = document.getElementById("passwordMsg");
  var current_password = document.getElementById("current_password").value;
  var new_password = document.getElementById("new_password").value;
  var confirm_password = document.getElementById("confirm_password").value;

  if (new_password !== confirm_password) {
    msg.style.color = "red";
    msg.textContent = "Passwords do not match";
    return;
  }

  try {
    var r = await fetch("../api/password_change.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify({
        csrf: window.APP.csrf,
        current_password: current_password,
        new_password: new_password,
        confirm_password: confirm_password
      })
    });
    var j = await r.json().catch(function(){ return { success:false, error:"invalid_response" }; });
    if (j.success) {
      msg.style.color = "green";
      msg.textContent = j.message || "Password updated";
      document.getElementById("passwordChangeForm").reset();
    } else {
      msg.style.color = "red";
      msg.textContent = j.error || "Failed";
    }
  } catch (e) {
    msg.style.color = "red";
    msg.textContent = "Request failed";
  }
});

loadProfile();
</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>
