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

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);
$canEdit = ($roleId === 1 || $roleId === 5);
$canRequest = ($roleId === 4);
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user["id"] ?? 0));

$workerId = (int)($_GET["worker_id"] ?? 0);
if ($workerId <= 0) {
    http_response_code(400);
    echo "Invalid worker.";
    exit;
}

$stmt = $pdo->prepare("
    SELECT
        w.id, w.user_id, w.first_name, w.last_name, w.status,
        u.email AS worker_email,
        up.skills, up.languages, up.country, up.availability, up.certificates, up.cv_url,
        up.location, up.bio, up.photo_url, up.youtube_url, up.desired_salary_from, up.desired_salary_to,
        up.video_interview, up.video_work, up.position,
        GROUP_CONCAT(DISTINCT COALESCE(s.name, s2.name) ORDER BY COALESCE(s.name, s2.name) SEPARATOR ', ') AS skill_names
    FROM workers w
    LEFT JOIN users u ON u.id = w.user_id
    LEFT JOIN user_profiles up ON up.user_id = w.user_id
    LEFT JOIN user_skills us ON us.user_id = w.user_id
    LEFT JOIN skills s ON s.id = us.skill_id
    LEFT JOIN skills s2 ON FIND_IN_SET(CAST(s2.id AS CHAR), REPLACE(COALESCE(up.skills, ''), ' ', '')) > 0
    WHERE w.id = ?
    GROUP BY
        w.id, w.user_id, w.first_name, w.last_name, w.status,
        u.email, up.skills, up.languages, up.country, up.availability, up.certificates, up.cv_url,
        up.location, up.bio, up.photo_url, up.youtube_url, up.desired_salary_from, up.desired_salary_to,
        up.video_interview, up.video_work, up.position
    LIMIT 1
");
$stmt->execute([$workerId]);
$worker = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$worker) {
    http_response_code(404);
    echo "Worker not found.";
    exit;
}

$fullName = trim((string)($worker["first_name"] ?? "") . " " . (string)($worker["last_name"] ?? ""));
if ($fullName === "") $fullName = "Worker #" . (int)$worker["id"];

$img = trim((string)($worker["photo_url"] ?? ""));
if ($img === "") $img = "assets/images/400x530_1.jpg";

function esc($v) { return htmlspecialchars((string)$v, ENT_QUOTES, "UTF-8"); }

$skillText = trim((string)($worker["skill_names"] ?? ""));
if ($skillText === "") {
    $rawSkills = trim((string)($worker["skills"] ?? ""));
    if ($rawSkills !== "" && !preg_match('/^\d+(?:\s*,\s*\d+)*$/', $rawSkills)) {
        $skillText = $rawSkills;
    }
}
if ($skillText === "") {
    $skillText = "n/a";
}

function youtubeIdFromInput(string $value): string
{
    $value = trim($value);
    if ($value === "") return "";
    if (preg_match('/^[A-Za-z0-9_-]{11}$/', $value)) return $value;

    $parts = @parse_url($value);
    if (!is_array($parts)) return "";

    $host = strtolower($parts["host"] ?? "");
    $path = $parts["path"] ?? "";
    $query = $parts["query"] ?? "";

    if ($host === "youtu.be") {
        $id = trim($path, "/");
        if (preg_match('/^[A-Za-z0-9_-]{11}$/', $id)) return $id;
    }

    if (strpos($host, "youtube.com") !== false) {
        parse_str($query, $q);
        if (!empty($q["v"]) && preg_match('/^[A-Za-z0-9_-]{11}$/', $q["v"])) {
            return $q["v"];
        }
        if (preg_match('~/embed/([A-Za-z0-9_-]{11})~', $path, $m)) return $m[1];
        if (preg_match('~/shorts/([A-Za-z0-9_-]{11})~', $path, $m)) return $m[1];
    }

    return "";
}

$youtubeId = youtubeIdFromInput((string)($worker["youtube_url"] ?? ""));
$youtubeEmbed = $youtubeId !== "" ? "https://www.youtube-nocookie.com/embed/" . rawurlencode($youtubeId) . "?rel=0&modestbranding=1&playsinline=1&controls=1" : "";

$selfHostedVideoUrl = "";
$rawVideoUrl = trim((string)($worker["cv_url"] ?? ""));
if ($rawVideoUrl !== "") {
    $ext = strtolower(pathinfo(parse_url($rawVideoUrl, PHP_URL_PATH) ?? "", PATHINFO_EXTENSION));
    if (in_array($ext, ["mp4", "webm", "ogg"], true)) {
        $selfHostedVideoUrl = $rawVideoUrl;
    }
}

$salaryFrom = trim((string)($worker["desired_salary_from"] ?? ""));
$salaryTo = trim((string)($worker["desired_salary_to"] ?? ""));
$salaryText = "n/a";

$companyPlanCode = "";
if ($roleId === 4) {
    try {
        $subStmt = $pdo->prepare("
            SELECT plan_code
            FROM company_subscriptions
            WHERE company_id = ?
              AND status = 'active'
              AND (expires_at IS NULL OR expires_at >= NOW())
            ORDER BY id DESC
            LIMIT 1
        ");
        $subStmt->execute([(int)($user["id"] ?? 0)]);
        $sub = $subStmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $companyPlanCode = strtoupper(trim((string)($sub["plan_code"] ?? "")));
    } catch (Throwable $e) {
        $companyPlanCode = "";
    }
}

try {
    $salaryStmt = $pdo->prepare("
        SELECT desired_salary_from, desired_salary_to
        FROM user_profiles
        WHERE user_id = ?
        LIMIT 1
    ");
    $salaryStmt->execute([(int)($worker["user_id"] ?? 0)]);
    $salaryRow = $salaryStmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $salaryFrom = trim((string)($salaryRow["desired_salary_from"] ?? ""));
    $salaryTo = trim((string)($salaryRow["desired_salary_to"] ?? ""));
} catch (Throwable $e) {
    $salaryFrom = "";
    $salaryTo = "";
}

if ($salaryFrom !== "" && $salaryTo !== "") $salaryText = "$" . esc($salaryFrom) . " - $" . esc($salaryTo);
elseif ($salaryFrom !== "") $salaryText = "from $" . esc($salaryFrom);
elseif ($salaryTo !== "") $salaryText = "to $" . esc($salaryTo);

$canSeeExperience = ($roleId !== 4) || in_array($companyPlanCode, ["COMPANY_PRO", "COMPANY_ENTERPRISE"], true);
$canSeeVideoInterview = ($roleId !== 4) || in_array($companyPlanCode, ["COMPANY_PRO", "COMPANY_ENTERPRISE"], true);
$canSeeVideoWork = ($roleId !== 4) || ($companyPlanCode === "COMPANY_ENTERPRISE");
$canSeeSalary = ($roleId !== 4) || ($companyPlanCode === "COMPANY_ENTERPRISE");
$canSeeDocuments = ($roleId === 1 || $roleId === 5) || ($roleId === 4 && $companyPlanCode === "COMPANY_ENTERPRISE");

$videoInterviewUrl = trim((string)($worker["video_interview"] ?? ""));
$videoWorkUrl = trim((string)($worker["video_work"] ?? ""));

function parseVideoSource(string $value): array
{
    $url = trim($value);
    if ($url === "") {
        return ["type" => "", "embed" => "", "direct" => "", "mime" => ""];
    }

    $ytId = youtubeIdFromInput($url);
    if ($ytId !== "") {
        return [
            "type" => "youtube",
            "embed" => "https://www.youtube-nocookie.com/embed/" . rawurlencode($ytId) . "?rel=0&modestbranding=1&playsinline=1&controls=1",
            "direct" => "",
            "mime" => ""
        ];
    }

    $parts = @parse_url($url);
    $host = strtolower((string)($parts["host"] ?? ""));
    $path = (string)($parts["path"] ?? "");

    if (strpos($host, "vimeo.com") !== false) {
        if (preg_match('~/(?:video/)?([0-9]+)(?:$|[/?])~', $path, $m)) {
            return [
                "type" => "vimeo",
                "embed" => "https://player.vimeo.com/video/" . rawurlencode($m[1]),
                "direct" => "",
                "mime" => ""
            ];
        }
    }

    $ext = strtolower(pathinfo(parse_url($url, PHP_URL_PATH) ?? "", PATHINFO_EXTENSION));
    if (in_array($ext, ["mp4", "webm", "ogg"], true)) {
        $mime = "video/" . ($ext === "ogg" ? "ogg" : $ext);
        return [
            "type" => "direct",
            "embed" => "",
            "direct" => $url,
            "mime" => $mime
        ];
    }

    return ["type" => "", "embed" => "", "direct" => "", "mime" => ""];
}

$videoInterviewSource = parseVideoSource($videoInterviewUrl);
$videoWorkSource = parseVideoSource($videoWorkUrl);
?>
<!DOCTYPE HTML>
<html lang="<?= esc(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= esc($fullName) ?> - Worker Profile</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/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">
<style>
.navbar .logo img{max-height:42px;width:auto}
.listing_price.readonly{font-size:22px}
</style>
</head>
<body>
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top" data-spy="affix" data-offset-top="10">
<div class="container">
<div class="navbar-header">
<div class="logo"><a href="dashboard.php"><img src="assets/images/logo.png" alt="image"/></a></div>
<button id="menu_slide" data-target="#navigation" aria-expanded="false" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
<span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navigation">
<ul class="nav navbar-nav">
<li><a href="workers.php">Lista</a></li>
</ul>
<div class="submit_listing"><a href="workers.php" class="btn outline-btn"><i class="fa fa-arrow-left"></i> Back</a></div>
</div>
</div>
</nav>
</header>

<section id="listing_detail_banner" class="parallex-bg" style="margin-top:70px;">
<div id="listing_img_slider"><div class="owl-carousel owl-theme"><div class="item"><img src="<?= esc($img) ?>" alt="image"></div><div class="item"><img src="<?= esc($img) ?>" alt="image"></div></div></div>
<div class="view_map"><a href="#single_map" class="js-target-scroll"><i class="fa fa-map-marker"></i></a></div>
</section>

<section class="listing_detail_header">
<div class="container">
<h1><?= esc($fullName) ?></h1>
<p><?= esc($worker["status"] ?: "n/a") ?></p>
</div>
</section>

<section class="listing_info_wrap">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="ElemoListing_detail">
<div class="pricing_info">
<p class="listing_price readonly" id="salaryTextView"><?= $salaryText ?></p>
<div class="listing_message">
  <?php if ($canEdit): ?>
  <a class="btn" id="toggleEditBtn"><i class="fa fa-pencil"></i> Edit profile</a>
  <?php endif; ?>
  <?php if ($canRequest): ?>
  <a class="btn" id="requestWorkerBtn"><i class="fa fa-paper-plane"></i> Request</a>
  <?php endif; ?>
  <?php if (!$canEdit && !$canRequest): ?>
  <a class="btn"><i class="fa fa-lock"></i> Read only</a>
  <?php endif; ?>
</div>
</div>

<?php if ($canEdit): ?>
<div class="dashboard-list-box" id="workerEditBox" style="display:none;margin:15px 0;">
  <h4>Edit Worker Profile</h4>
  <div class="padding-20">
    <input type="hidden" id="editCsrf" value="<?= esc($csrf) ?>">
    <input type="hidden" id="editWorkerId" value="<?= (int)$worker["id"] ?>">
    <input type="hidden" id="editWorkerUserId" value="<?= (int)$worker["user_id"] ?>">

    <div class="row">
      <div class="col-md-6 form-group">
        <label class="label-title">Languages</label>
        <input type="text" id="edit_languages" class="form-control" value="<?= esc($worker["languages"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Country</label>
        <input type="text" id="edit_country" class="form-control" value="<?= esc($worker["country"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Availability</label>
        <input type="date" id="edit_availability" class="form-control" value="<?= esc($worker["availability"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Location</label>
        <input type="text" id="edit_location" class="form-control" value="<?= esc($worker["location"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Desired salary (from)</label>
        <input type="number" min="0" id="edit_desired_salary_from" class="form-control" value="<?= esc($salaryFrom) ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Desired salary (to)</label>
        <input type="number" min="0" id="edit_desired_salary_to" class="form-control" value="<?= esc($salaryTo) ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Skills</label>
        <input type="text" id="edit_skills" class="form-control" value="<?= esc($worker["skills"] ?? "") ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Certificates</label>
        <textarea id="edit_certificates" class="form-control"><?= esc($worker["certificates"] ?? "") ?></textarea>
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">CV URL</label>
        <input type="url" id="edit_cv_url" class="form-control" value="<?= esc($worker["cv_url"] ?? "") ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Photo URL</label>
        <input type="url" id="edit_photo_url" class="form-control" value="<?= esc($worker["photo_url"] ?? "") ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">YouTube URL</label>
        <input type="url" id="edit_youtube_url" class="form-control" value="<?= esc($worker["youtube_url"] ?? "") ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Bio</label>
        <textarea id="edit_bio" class="form-control" rows="4"><?= esc($worker["bio"] ?? "") ?></textarea>
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Video interview (YouTube link)</label>
        <input type="url" id="edit_video_interview" class="form-control" placeholder="https://www.youtube.com/watch?v=..." value="<?= esc($videoInterviewUrl) ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Video work (YouTube link)</label>
        <input type="url" id="edit_video_work" class="form-control" placeholder="https://www.youtube.com/watch?v=..." value="<?= esc($videoWorkUrl) ?>">
      </div>
      <div class="col-md-12">
        <button type="button" class="btn btn-primary" id="saveWorkerProfileBtn">Save Changes</button>
        <span id="workerEditMsg" style="margin-left:10px;"></span>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title"><a role="button" data-toggle="collapse" data-parent="#accordion" href="#description"><i class="fa fa-file-text-o"></i> O radniku</a></h4></div>
<div id="description" class="panel-collapse collapse in"><div class="panel-body"><p><?= nl2br(esc($worker["bio"] ?: "No bio.")) ?></p></div></div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title"><a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#amenities"><i class="fa fa-align-left"></i> Veštine</a></h4></div>
<div id="amenities" class="panel-collapse collapse"><div class="panel-body"><ul>
<li><a><i class="fa fa-cogs"></i> <?= esc($skillText) ?></a></li>
<li><a><i class="fa fa-language"></i> <?= esc($worker["languages"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-map-marker"></i> <?= esc($worker["country"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-map"></i> <?= esc($worker["location"] ?: "n/a") ?></a></li>
<?php if ($canSeeExperience): ?>
<li><a><i class="fa fa-briefcase"></i> <?= esc($worker["position"] ?: "n/a") ?></a></li>
<?php endif; ?>
</ul></div></div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title"><a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#dostupnost"><i class="fa fa-calendar-check-o"></i> Dostupnost</a></h4></div>
<div id="dostupnost" class="panel-collapse collapse"><div class="panel-body"><ul><li><span class="hours_title"><i class="fa fa-clock-o"></i><?= esc($worker["availability"] ?: "n/a") ?></span></li></ul></div></div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title"><a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#docs"><i class="fa fa-file"></i> Dokumenta</a></h4></div>
<div id="docs" class="panel-collapse collapse"><div class="panel-body">
<?php if ($canSeeDocuments): ?>
<p><strong>Certificates:</strong> <?= nl2br(esc($worker["certificates"] ?: "n/a")) ?></p>
<p><strong>CV:</strong> <?php if (!empty($worker["cv_url"])): ?><a href="<?= esc($worker["cv_url"]) ?>" target="_blank" rel="noopener">Open CV</a><?php else: ?>n/a<?php endif; ?></p>
<?php else: ?>
<p><strong>Documentation:</strong> Hidden (admin only)</p>
<?php endif; ?>
</div></div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title"><a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#video_intervju"><i class="fa fa-video-camera"></i> Video intervju</a></h4></div>
<div id="video_intervju" class="panel-collapse collapse"><div class="panel-body">
<?php if (!$canSeeVideoInterview): ?>
<p>Video interview available on PRO/ENTERPRISE package.</p>
<?php elseif ($videoInterviewSource["type"] === "direct"): ?>
<div class="listing_video" style="position:relative;" oncontextmenu="return false;">
  <video id="customVideoInterview" style="width:100%;min-height:320px;background:#000;" controls controlsList="nodownload noplaybackrate" preload="metadata">
    <source src="<?= esc($videoInterviewSource["direct"]) ?>" type="<?= esc($videoInterviewSource["mime"]) ?>">
    Your browser does not support HTML5 video.
  </video>
  <div style="margin-top:10px;display:flex;gap:10px;flex-wrap:wrap;">
    <button type="button" class="btn btn-sm btn-default" onclick="togglePlayPauseHtml5Interview()"><i class="fa fa-play"></i>/<i class="fa fa-pause"></i></button>
    <button type="button" class="btn btn-sm btn-default" onclick="toggleMuteHtml5Interview()"><i class="fa fa-volume-off"></i>/<i class="fa fa-volume-up"></i></button>
    <button type="button" class="btn btn-sm btn-default" onclick="toggleFullscreenHtml5Interview()"><i class="fa fa-arrows-alt"></i> Fullscreen</button>
  </div>
</div>
<?php elseif (in_array($videoInterviewSource["type"], ["youtube", "vimeo"], true)): ?>
<div class="listing_video" style="position:relative;" oncontextmenu="return false;">
  <iframe
    id="customVideoInterviewFrame"
    class="mfp-iframe"
    src="<?= esc($videoInterviewSource["embed"]) ?>"
    allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
    allowfullscreen
    referrerpolicy="strict-origin-when-cross-origin"
    style="width:100%;min-height:320px;border:0;"
  ></iframe>
</div>
<?php elseif ($selfHostedVideoUrl !== ""): ?>
<div class="listing_video" style="position:relative;" oncontextmenu="return false;">
  <video id="customVideo" style="width:100%;min-height:320px;background:#000;" controls controlsList="nodownload noplaybackrate" preload="metadata">
    <source src="<?= esc($selfHostedVideoUrl) ?>" type="video/<?= esc(pathinfo(parse_url($selfHostedVideoUrl, PHP_URL_PATH) ?? "", PATHINFO_EXTENSION)) ?>">
    Your browser does not support HTML5 video.
  </video>
  <div style="margin-top:10px;display:flex;gap:10px;flex-wrap:wrap;">
    <button type="button" class="btn btn-sm btn-default" onclick="togglePlayPauseHtml5()"><i class="fa fa-play"></i>/<i class="fa fa-pause"></i></button>
    <button type="button" class="btn btn-sm btn-default" onclick="toggleMuteHtml5()"><i class="fa fa-volume-off"></i>/<i class="fa fa-volume-up"></i></button>
    <button type="button" class="btn btn-sm btn-default" onclick="toggleFullscreenHtml5()"><i class="fa fa-arrows-alt"></i> Fullscreen</button>
  </div>
</div>
<?php elseif ($youtubeEmbed !== ""): ?>
<div class="listing_video" style="position:relative;" oncontextmenu="return false;">
  <iframe
    id="customYoutubeFrame"
    class="mfp-iframe"
    src="<?= esc($youtubeEmbed) ?>"
    allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
    allowfullscreen
    referrerpolicy="strict-origin-when-cross-origin"
    style="width:100%;min-height:320px;border:0;"
  ></iframe>
</div>
<?php else: ?>
<p>Video unavailable.</p>
<?php endif; ?>
</div></div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title"><a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#video_work"><i class="fa fa-film"></i> Video work</a></h4></div>
<div id="video_work" class="panel-collapse collapse"><div class="panel-body">
<?php if (!$canSeeVideoWork): ?>
<p>Video work available on ENTERPRISE package.</p>
<?php elseif ($videoWorkSource["type"] === "direct"): ?>
<div class="listing_video" style="position:relative;" oncontextmenu="return false;">
  <video id="customVideoWork" style="width:100%;min-height:320px;background:#000;" controls controlsList="nodownload noplaybackrate" preload="metadata">
    <source src="<?= esc($videoWorkSource["direct"]) ?>" type="<?= esc($videoWorkSource["mime"]) ?>">
    Your browser does not support HTML5 video.
  </video>
  <div style="margin-top:10px;display:flex;gap:10px;flex-wrap:wrap;">
    <button type="button" class="btn btn-sm btn-default" onclick="togglePlayPauseHtml5Work()"><i class="fa fa-play"></i>/<i class="fa fa-pause"></i></button>
    <button type="button" class="btn btn-sm btn-default" onclick="toggleMuteHtml5Work()"><i class="fa fa-volume-off"></i>/<i class="fa fa-volume-up"></i></button>
    <button type="button" class="btn btn-sm btn-default" onclick="toggleFullscreenHtml5Work()"><i class="fa fa-arrows-alt"></i> Fullscreen</button>
  </div>
</div>
<?php elseif (in_array($videoWorkSource["type"], ["youtube", "vimeo"], true)): ?>
<div class="listing_video" style="position:relative;" oncontextmenu="return false;">
  <iframe
    id="customVideoWorkFrame"
    class="mfp-iframe"
    src="<?= esc($videoWorkSource["embed"]) ?>"
    allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
    allowfullscreen
    referrerpolicy="strict-origin-when-cross-origin"
    style="width:100%;min-height:320px;border:0;"
  ></iframe>
</div>
<?php else: ?>
<p>Video work unavailable.</p>
<?php endif; ?>
</div></div>
</div>

</div>
</div>
</div>

<div class="col-md-4">
<div class="ElemoListing_sidebar">
<?php if ($roleId !== 4): ?>
<div class="sidebar_wrap listing_contact_info">
<div class="widget_title"><h6>Contact Info</h6></div>
<ul>
<li><i class="fa fa-envelope"></i> <?= esc($worker["worker_email"] ?: "n/a") ?></li>
<li><i class="fa fa-map-marker"></i> <?= esc($worker["country"] ?: "n/a") ?></li>
<li><i class="fa fa-money"></i> Desired salary: <?= $canSeeSalary ? $salaryText : "Visible on ENTERPRISE package" ?></li>
</ul>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</section>

<script>
(function(){
  var REQUEST_WORKER_ID = <?= (int)$worker["id"] ?>;
  var REQUEST_CSRF = "<?= esc($csrf) ?>";
  var toggleEditBtn = document.getElementById("toggleEditBtn");
  var workerEditBox = document.getElementById("workerEditBox");
  if (toggleEditBtn && workerEditBox) {
    toggleEditBtn.addEventListener("click", function(){
      workerEditBox.style.display = (workerEditBox.style.display === "none" || workerEditBox.style.display === "") ? "block" : "none";
    });

    var saveBtn = document.getElementById("saveWorkerProfileBtn");
    if (saveBtn) {
      saveBtn.addEventListener("click", async function(){
        var msg = document.getElementById("workerEditMsg");
        msg.style.color = "#555";
        msg.textContent = "Saving...";

        var payload = {
          csrf: document.getElementById("editCsrf").value,
          worker_id: parseInt(document.getElementById("editWorkerId").value, 10),
          user_id: parseInt(document.getElementById("editWorkerUserId").value, 10),
          skills: (document.getElementById("edit_skills").value || "").trim(),
          languages: (document.getElementById("edit_languages").value || "").trim(),
          country: (document.getElementById("edit_country").value || "").trim(),
          availability: (document.getElementById("edit_availability").value || "").trim(),
          certificates: (document.getElementById("edit_certificates").value || "").trim(),
          cv_url: (document.getElementById("edit_cv_url").value || "").trim(),
          location: (document.getElementById("edit_location").value || "").trim(),
          bio: (document.getElementById("edit_bio").value || "").trim(),
          photo_url: (document.getElementById("edit_photo_url").value || "").trim(),
          youtube_url: (document.getElementById("edit_youtube_url").value || "").trim(),
          video_interview: (document.getElementById("edit_video_interview").value || "").trim(),
          video_work: (document.getElementById("edit_video_work").value || "").trim(),
          desired_salary_from: (document.getElementById("edit_desired_salary_from").value || "").trim(),
          desired_salary_to: (document.getElementById("edit_desired_salary_to").value || "").trim()
        };

        try {
          var r = await fetch("../api/profile_update.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            credentials: "same-origin",
            body: JSON.stringify(payload)
          });
          var j = await r.json().catch(function(){ return { status:"error", message:"invalid_response" }; });
          if (j.status === "success") {
            msg.style.color = "green";
            msg.textContent = "Saved";
            window.location.reload();
          } else {
            msg.style.color = "red";
            msg.textContent = j.message || "Failed";
          }
        } catch (e) {
          msg.style.color = "red";
          msg.textContent = "Request failed";
        }
      });
    }
  }

  var requestBtn = document.getElementById("requestWorkerBtn");
  if (requestBtn) {
    requestBtn.addEventListener("click", async function(){
      if (!confirm("Send request for this worker?")) return;
      requestBtn.disabled = true;
      var original = requestBtn.innerHTML;
      requestBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Sending...';
      try {
        var r = await fetch("../api/requests.php", {
          method: "POST",
          headers: { "Content-Type":"application/json" },
          credentials: "same-origin",
          body: JSON.stringify({
            csrf: REQUEST_CSRF,
            worker_id: REQUEST_WORKER_ID
          })
        });
        var j = await r.json().catch(function(){ return { success:false, error:"invalid_response" }; });
        if (j.success) {
          alert("Request sent.");
        } else {
          alert(j.error || "Request failed");
        }
      } catch (e) {
        alert("Request failed");
      } finally {
        requestBtn.disabled = false;
        requestBtn.innerHTML = original;
      }
    });
  }
})();
</script>
<script>
(function(){
  var html5Video = document.getElementById("customVideo");
  if (html5Video) {
    window.togglePlayPauseHtml5 = function() {
      if (html5Video.paused) html5Video.play();
      else html5Video.pause();
    };
    window.toggleMuteHtml5 = function() {
      html5Video.muted = !html5Video.muted;
    };
    window.toggleFullscreenHtml5 = function() {
      if (html5Video.requestFullscreen) html5Video.requestFullscreen();
      else if (html5Video.webkitRequestFullscreen) html5Video.webkitRequestFullscreen();
      else if (html5Video.msRequestFullscreen) html5Video.msRequestFullscreen();
    };
  }

  var html5Interview = document.getElementById("customVideoInterview");
  if (html5Interview) {
    window.togglePlayPauseHtml5Interview = function() {
      if (html5Interview.paused) html5Interview.play();
      else html5Interview.pause();
    };
    window.toggleMuteHtml5Interview = function() {
      html5Interview.muted = !html5Interview.muted;
    };
    window.toggleFullscreenHtml5Interview = function() {
      if (html5Interview.requestFullscreen) html5Interview.requestFullscreen();
      else if (html5Interview.webkitRequestFullscreen) html5Interview.webkitRequestFullscreen();
      else if (html5Interview.msRequestFullscreen) html5Interview.msRequestFullscreen();
    };
  }

  var html5Work = document.getElementById("customVideoWork");
  if (html5Work) {
    window.togglePlayPauseHtml5Work = function() {
      if (html5Work.paused) html5Work.play();
      else html5Work.pause();
    };
    window.toggleMuteHtml5Work = function() {
      html5Work.muted = !html5Work.muted;
    };
    window.toggleFullscreenHtml5Work = function() {
      if (html5Work.requestFullscreen) html5Work.requestFullscreen();
      else if (html5Work.webkitRequestFullscreen) html5Work.webkitRequestFullscreen();
      else if (html5Work.msRequestFullscreen) html5Work.msRequestFullscreen();
    };
  }
})();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/interface.js"></script>
<script src="assets/js/owl.carousel.min.js"></script>
</body>
</html>
