<?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);
$csrf = csrfToken();
$avatarUrl = resolveUserAvatarUrl($pdo, (int)($user["id"] ?? 0));

$agencyId = (int)($_GET["agency_id"] ?? 0);
if ($agencyId <= 0) {
    http_response_code(400);
    echo "Invalid agency.";
    exit;
}

$stmt = $pdo->prepare("
    SELECT
        u.id, u.email, u.agency_is_partner, u.agency_name, u.agency_address, u.agency_tax_id,
        up.country, up.location, up.languages, up.bio, up.photo_url
    FROM users u
    LEFT JOIN user_profiles up ON up.user_id = u.id
    WHERE u.id = ? AND u.role_id = 3
    LIMIT 1
");
$stmt->execute([$agencyId]);
$agency = $stmt->fetch(PDO::FETCH_ASSOC);

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

$agencyName = trim((string)($agency["agency_name"] ?? ""));
if ($agencyName === "") $agencyName = (string)($agency["email"] ?? ("Agency #" . $agencyId));

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

function esc($v) { return htmlspecialchars((string)$v, ENT_QUOTES, "UTF-8"); }
?>
<!DOCTYPE html>
<html lang="<?= esc(currentLang()) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= esc($agencyName) ?> - Agency Profile</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/owl.carousel.min.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}</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="agencies.php">Lista</a></li></ul>
<div class="submit_listing"><a href="agencies.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($agencyName) ?></h1>
<p><?= esc($agency["location"] ?: "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">
<?php if ($canEdit): ?>
<div class="dashboard-list-box" id="agencyEditBox" style="margin:0 0 15px 0;">
  <h4>Edit Agency Profile</h4>
  <div class="padding-20">
    <input type="hidden" id="agencyEditCsrf" value="<?= esc($csrf) ?>">
    <input type="hidden" id="agencyEditUserId" value="<?= (int)$agency["id"] ?>">
    <div class="row">
      <div class="col-md-6 form-group">
        <label class="label-title">Agency Name</label>
        <input type="text" id="agency_name" class="form-control" value="<?= esc($agency["agency_name"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">PIB</label>
        <input type="text" id="agency_tax_id" class="form-control" value="<?= esc($agency["agency_tax_id"] ?? "") ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Address</label>
        <input type="text" id="agency_address" class="form-control" value="<?= esc($agency["agency_address"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Country</label>
        <input type="text" id="agency_country" class="form-control" value="<?= esc($agency["country"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Location</label>
        <input type="text" id="agency_location" class="form-control" value="<?= esc($agency["location"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Languages</label>
        <input type="text" id="agency_languages" class="form-control" value="<?= esc($agency["languages"] ?? "") ?>">
      </div>
      <div class="col-md-6 form-group">
        <label class="label-title">Photo URL</label>
        <input type="url" id="agency_photo_url" class="form-control" value="<?= esc($agency["photo_url"] ?? "") ?>">
      </div>
      <div class="col-md-12 form-group">
        <label class="label-title">Bio</label>
        <textarea id="agency_bio" class="form-control" rows="4"><?= esc($agency["bio"] ?? "") ?></textarea>
      </div>
      <div class="col-md-12">
        <button type="button" class="btn btn-primary" id="saveAgencyProfileBtn">Save Changes</button>
        <span id="agencyEditMsg" 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 agenciji</a></h4></div>
<div id="description" class="panel-collapse collapse in"><div class="panel-body"><p><?= nl2br(esc($agency["bio"] ?: "No description.")) ?></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> Detalji</a></h4></div>
<div id="amenities" class="panel-collapse collapse"><div class="panel-body"><ul>
<li><a><i class="fa fa-envelope"></i> <?= esc($agency["email"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-map-marker"></i> <?= esc($agency["country"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-map"></i> <?= esc($agency["location"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-language"></i> <?= esc($agency["languages"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-building"></i> <?= esc($agency["agency_address"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-phone"></i> n/a</a></li>
<li><a><i class="fa fa-id-card"></i> <?= esc($agency["agency_tax_id"] ?: "n/a") ?></a></li>
<li><a><i class="fa fa-certificate"></i> Partner: <?= ((int)($agency["agency_is_partner"] ?? 0) === 1) ? "Yes" : "No" ?></a></li>
</ul></div></div>
</div>
</div>
</div>
</div>

<div class="col-md-4">
<div class="ElemoListing_sidebar">
<div class="sidebar_wrap listing_contact_info">
<div class="widget_title"><h6>Contact Info</h6></div>
<ul>
<li><i class="fa fa-map-marker"></i> <?= esc($agency["agency_address"] ?: $agency["location"] ?: "n/a") ?></li>
<li><i class="fa fa-phone"></i> n/a</li>
<li><i class="fa fa-envelope"></i> <?= esc($agency["email"] ?: "n/a") ?></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>

<script>
(function(){
  var saveBtn = document.getElementById("saveAgencyProfileBtn");
  if (!saveBtn) return;

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

    var payload = {
      csrf: document.getElementById("agencyEditCsrf").value,
      user_id: parseInt(document.getElementById("agencyEditUserId").value, 10),
      agency_name: (document.getElementById("agency_name").value || "").trim(),
      agency_tax_id: (document.getElementById("agency_tax_id").value || "").trim(),
      agency_address: (document.getElementById("agency_address").value || "").trim(),
      country: (document.getElementById("agency_country").value || "").trim(),
      location: (document.getElementById("agency_location").value || "").trim(),
      languages: (document.getElementById("agency_languages").value || "").trim(),
      photo_url: (document.getElementById("agency_photo_url").value || "").trim(),
      bio: (document.getElementById("agency_bio").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";
    }
  });
})();
</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>
