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

requirePageAuth();
$user = getAuthUser();
$roleId = (int)($user["role_id"] ?? 0);

if ($roleId !== 4) {
    header("Location: dashboard.php");
    exit;
}

$csrf = csrfToken();
$title = "Company Subscription";
$prefPlan = trim((string)($_GET["plan_code"] ?? ""));
$prefEmail = trim((string)($_GET["company_email"] ?? ""));

$companyNamePref = (string)($user["company_name"] ?? "");
$companyAddressPref = (string)($user["company_address"] ?? "");
$companyTaxPref = (string)($user["company_tax_id"] ?? "");
$userEmailPref = (string)($user["email"] ?? "");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?= htmlspecialchars($title, ENT_QUOTES, "UTF-8") ?> - Konzona Hub</title>
  <link rel="stylesheet" href="assets/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/css/style.css">
  <link rel="stylesheet" href="assets/css/dashboard.css">
  <style>
    .navbar .logo img { max-height: 42px; width: auto; }
    .plan-card { border: 1px solid #ddd; border-radius: 8px; padding: 16px; margin-bottom: 12px; cursor: pointer; }
    .plan-card.active { border-color: #3f51b5; background: #f5f7ff; }
    .invoice-box { background: #fafafa; border: 1px dashed #999; padding: 15px; border-radius: 8px; margin-top: 15px; }
    .fields-row .form-control { margin-bottom: 10px; }
    .hint { color: #666; font-size: 13px; margin-bottom: 12px; }
  </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="pricing.php">Pricing</a></li>
        </ul>
      </div>
    </div>
  </nav>
</header>
<div class="container" style="max-width:980px;margin-top:110px;">
  <div class="row">
    <div class="col-md-12">
      <h2><?= htmlspecialchars($title, ENT_QUOTES, "UTF-8") ?></h2>
      <p id="statusText">Loading...</p>
      <input type="hidden" id="csrf_token" value="<?= htmlspecialchars($csrf, ENT_QUOTES, "UTF-8") ?>">
      <input type="hidden" id="pref_plan" value="<?= htmlspecialchars($prefPlan, ENT_QUOTES, "UTF-8") ?>">
    </div>
  </div>

  <div class="row fields-row" id="identityFields">
    <div class="col-md-3"><input class="form-control" id="company_name" placeholder="Company name"></div>
    <div class="col-md-3"><input class="form-control" id="company_address" placeholder="Company address"></div>
    <div class="col-md-3"><input class="form-control" id="company_tax_id" placeholder="PIB / Tax ID (optional)"></div>
    <div class="col-md-3"><input class="form-control" id="company_email" type="email" placeholder="Email for payment slip" value="<?= htmlspecialchars($prefEmail, ENT_QUOTES, "UTF-8") ?>"></div>
  </div>
  <div class="row" id="specialCriteriaRow" style="display:none;">
    <div class="col-md-12">
      <label for="special_criteria"><strong>Special worker criteria (for strongest package when no worker is found)</strong></label>
      <textarea class="form-control" id="special_criteria" rows="3" placeholder="Describe required skills, language, experience, location, certifications..."></textarea>
    </div>
  </div>
  <div class="hint">Pricing applies only to companies. Agencies do not have pricing packages.</div>

  <div class="row" style="margin-top:15px;">
    <div class="col-md-12">
      <div id="plansWrap"></div>
      <button class="btn btn-primary" id="generateBtn">Generate Payment Slip</button>
      <a href="pricing.php" class="btn btn-default">Back to Pricing</a>
      <a href="logout.php" class="btn btn-default">Logout</a>
      <div id="msg" style="margin-top:10px;"></div>
      <div id="invoiceBox" class="invoice-box" style="display:none;"></div>
    </div>
  </div>
</div>

<script>
(function () {
  var csrf = document.getElementById("csrf_token").value;
  var selectedPlan = "";
  var preferredPlan = (document.getElementById("pref_plan").value || "").trim();

  var prefCompanyName = <?= json_encode($companyNamePref, JSON_UNESCAPED_UNICODE) ?>;
  var prefCompanyAddress = <?= json_encode($companyAddressPref, JSON_UNESCAPED_UNICODE) ?>;
  var prefCompanyTax = <?= json_encode($companyTaxPref, JSON_UNESCAPED_UNICODE) ?>;
  var prefUserEmail = <?= json_encode($userEmailPref, JSON_UNESCAPED_UNICODE) ?>;

  function esc(input) {
    var s = String(input == null ? "" : input);
    return s
    .split("&").join("&amp;")
    .split("<").join("&lt;")
    .split(">").join("&gt;")
    .split('"').join("&quot;")
    .split("'").join("&#039;");
  }

  function orderedCompanyPlans(plans) {
    return [
      { code: "COMPANY_BASIC", data: plans["COMPANY_BASIC"] || null, title: "Essence", subtitle: "brza selekcija" },
      { code: "COMPANY_PRO", data: plans["COMPANY_PRO"] || null, title: "Prime", subtitle: "detaljnija selekcija i filtriranje radnika" },
      { code: "COMPANY_ENTERPRISE", data: plans["COMPANY_ENTERPRISE"] || null, title: "Prestige", subtitle: "bez limita profila radnika" }
    ].filter(function (x) { return !!x.data; });
  }

  function renderFeaturesByCode(code) {
    var map = {
      "COMPANY_BASIC": ["2 Zahteva za radnike","7 dana pristup bazi","Osnovni profil radnika","Bez videa radnika","Ograničena podrška"],
      "COMPANY_PRO": ["5 zahteva za radnike","15 dana pristup bazi","Proširen prikaz profila radnika","Video intervju radnika","24/7 Podrška"],
      "COMPANY_ENTERPRISE": ["15 zahteva za radnike","30 dana pristup bazi","Pun prikaz profila radnika","Video intervju i sposobnosti","24/7 Podrška"]
    };
    return map[code] || [];
  }

  function renderPlans(plans) {
    var wrap = document.getElementById("plansWrap");
    wrap.innerHTML = "";
    var ordered = orderedCompanyPlans(plans || {});
    ordered.forEach(function (entry) {
      var code = entry.code;
      var p = entry.data || {};
      var div = document.createElement("div");
      div.className = "plan-card";
      div.setAttribute("data-code", code);

      var features = renderFeaturesByCode(code).map(function (f) {
        return "<li>" + esc(f) + "</li>";
      }).join("");

      div.innerHTML =
        "<h4 style='margin-top:0;'>" + esc(entry.title) + "</h4>" +
        "<p style='color:#666;'>" + esc(entry.subtitle) + "</p>" +
        "<div><strong>Amount:</strong> €" + esc(p.amount || "") + "</div>" +
        "<div><strong>Request limit:</strong> " + esc(p.limit || "") + "</div>" +
        "<ul style='margin-top:10px;'>" + features + "</ul>";

      div.onclick = function () {
        selectedPlan = code;
        var cards = document.querySelectorAll(".plan-card");
        for (var i = 0; i < cards.length; i++) { cards[i].classList.remove("active"); }
        div.classList.add("active");
        toggleSpecialCriteria();
      };

      wrap.appendChild(div);

      if (!selectedPlan && preferredPlan && preferredPlan === code) {
        selectedPlan = code;
        div.classList.add("active");
      }
    });

    if (!selectedPlan && ordered.length > 0) {
      selectedPlan = ordered[0].code;
      var first = wrap.querySelector(".plan-card");
      if (first) { first.classList.add("active"); }
    }

    toggleSpecialCriteria();
  }

  function toggleSpecialCriteria() {
    var row = document.getElementById("specialCriteriaRow");
    if (!row) return;
    row.style.display = (selectedPlan === "COMPANY_ENTERPRISE") ? "block" : "none";
  }

  function renderInvoice(inv) {
    if (!inv) return;
    var box = document.getElementById("invoiceBox");
    box.style.display = "block";
    box.innerHTML =
      "<h4>Payment Slip / Invoice</h4>" +
      "<p><strong>Name:</strong> " + esc(inv.company_name) + "</p>" +
      "<p><strong>Address:</strong> " + esc(inv.company_address) + "</p>" +
      "<p><strong>Tax ID:</strong> " + esc(inv.company_tax_id || "-") + "</p>" +
      "<p><strong>Email:</strong> " + esc(document.getElementById("company_email").value || "-") + "</p>" +
      "<p><strong>Plan:</strong> " + esc(inv.selected_plan) + "</p>" +
      "<p><strong>Amount:</strong> €" + esc(inv.amount_due) + "</p>" +
      "<p><strong>Reference:</strong> " + esc(inv.reference_number) + "</p>" +
      "<p><strong>Bank:</strong> " + esc(inv.bank_name) + " / " + esc(inv.bank_account) + " (" + esc(inv.bank_swift || "") + ")</p>" +
      "<p><strong>Deadline:</strong> " + esc(inv.payment_deadline) + "</p>" +
      "<p><strong>Status:</strong> " + esc(inv.status) + "</p>";
  }

  function setMessage(text, ok) {
    var msg = document.getElementById("msg");
    msg.style.color = ok ? "green" : "red";
    msg.textContent = text || "";
  }

  async function loadState() {
    var r = await fetch("../api/subscriptions.php", { credentials: "same-origin" });
    var j = await r.json().catch(function () { return { success: false }; });
    var statusText = document.getElementById("statusText");

    if (!j.success) {
      statusText.textContent = "Unable to load current payment state.";
      return;
    }

    var d = j.data || {};
    var sub = d.subscription || null;

    if (sub && sub.status === "active") {
      statusText.textContent = "Subscription active until: " + (sub.expires_at || "-");
    } else if (sub && sub.status === "expired") {
      statusText.textContent = "Subscription expired. Please generate and pay a new slip.";
    } else {
      statusText.textContent = "Subscription not active. Choose a package and generate payment slip.";
    }

    document.getElementById("company_name").value = (d.invoice && d.invoice.company_name) ? d.invoice.company_name : (prefCompanyName || "");
    document.getElementById("company_address").value = (d.invoice && d.invoice.company_address) ? d.invoice.company_address : (prefCompanyAddress || "");
    document.getElementById("company_tax_id").value = (d.invoice && d.invoice.company_tax_id) ? d.invoice.company_tax_id : (prefCompanyTax || "");
    if (!document.getElementById("company_email").value) {
      document.getElementById("company_email").value = prefUserEmail || "";
    }

    renderPlans(d.plans || {});
    if (d.invoice) { renderInvoice(d.invoice); }
  }

  document.getElementById("generateBtn").addEventListener("click", async function () {
    if (!selectedPlan) {
      setMessage("Please select a plan.", false);
      return;
    }

    var companyName = document.getElementById("company_name").value.trim();
    var companyAddress = document.getElementById("company_address").value.trim();
    var companyTaxId = document.getElementById("company_tax_id").value.trim();
    var companyEmail = document.getElementById("company_email").value.trim();

    if (!companyName || !companyAddress) {
      setMessage("Company name and address are required.", false);
      return;
    }

    if (!companyEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(companyEmail)) {
      setMessage("Valid company email is required.", false);
      return;
    }

    var payload = {
      csrf: csrf,
      plan_code: selectedPlan,
      company_name: companyName,
      company_address: companyAddress,
      company_tax_id: companyTaxId,
      company_email: companyEmail
    };

    if (selectedPlan === "COMPANY_ENTERPRISE") {
      payload.special_criteria = (document.getElementById("special_criteria").value || "").trim();
    }

    var r = await fetch("../api/subscriptions.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify(payload)
    });

    var j = await r.json().catch(function () {
      return { success: false, error: "invalid_response" };
    });

    if (j.success) {
      setMessage("Payment slip generated. Wait for admin confirmation.", true);
      await loadState();
    } else {
      setMessage(j.error || "Failed to generate payment slip.", false);
    }
  });

  loadState();
})();
</script>
</body>
</html>
