<?php
require_once __DIR__ . "/../../config/config.php";
require_once __DIR__ . "/../../includes/functions.php";
startSession(); requireLogin();
$db = Database::getInstance();
$page = "Support Desk";
$user = currentUser();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";
    // FIX (07 Jul 2026): support_tickets had no org concept at all —
    // added company_id (migration_support_tickets_company.sql) and
    // scoped everything below to the current org.
    $orgCompanies = orgCompanyIds($db);
    $companyId    = $orgCompanies[0] ?? 0;
    if ($action === "new_ticket") {
        $empId = $user["emp_id"] ?: postInt("employee_id");
        $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
        if (!$target || !in_array($target['company_id'], $orgCompanies)) {
            setFlash('error', 'Employee not found.');
            header("Location: ".BASE_URL."/modules/support/index.php"); exit;
        }
        $ticketNo = "TKT-" . strtoupper(substr(md5(uniqid()),0,6));
        $db->execute("INSERT INTO support_tickets (company_id,ticket_number,employee_id,category,subject,description,priority,status,created_by) VALUES (?,?,?,?,?,?,?,'open',?)",
            [$companyId,$ticketNo,$empId,post("category"),post("subject"),post("description"),post("priority"),$user["id"]]);
        setFlash("success","Ticket $ticketNo raised successfully.");
    } elseif ($action === "reply" || $action === "close") {
        $ticketId = $action === "reply" ? postInt("ticket_id") : postInt("id");
        $owned = $db->fetchOne("SELECT id FROM support_tickets WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$ticketId], $orgCompanies));
        if (!$owned) {
            setFlash('error', 'Ticket not found.');
        } elseif ($action === "reply") {
            $db->execute("INSERT INTO support_replies (ticket_id,reply_by,message,is_staff) VALUES (?,?,?,?)",
                [$ticketId,$user["id"],post("message"),1]);
            $db->execute("UPDATE support_tickets SET status=?,updated_at=NOW() WHERE id=?",[post("new_status"),$ticketId]);
            setFlash("success","Reply sent.");
        } else {
            $db->execute("UPDATE support_tickets SET status='closed',closed_at=NOW() WHERE id=?",[$ticketId]);
            setFlash("success","Ticket closed.");
        }
    }
    header("Location: ".BASE_URL."/modules/support/index.php"); exit;
}

$selTicket = cleanInt($_GET["ticket"] ?? 0);
// FIX: whitelist the filter value (was raw string concatenation into
// SQL — an injection path) and scope everything to the current org.
$filterOptions = ["all","open","in_progress","resolved","closed"];
$filter = in_array($_GET["filter"] ?? "", $filterOptions) ? $_GET["filter"] : "all";
[$orgClause, $orgParams] = orgScopeClause($db, 'st.company_id');
$where  = $orgClause;
$params = $orgParams;
if ($filter !== "all") { $where .= " AND st.status=?"; $params[] = $filter; }
$tickets   = $db->fetchAll("SELECT st.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code FROM support_tickets st LEFT JOIN employees e ON e.id=st.employee_id WHERE $where ORDER BY st.priority DESC,st.created_at DESC", $params);
// FIX: reject ?ticket=<other org's ticket>.
if ($selTicket && !in_array($selTicket, array_column($tickets, 'id'))) { $selTicket = 0; }
$ticket    = $selTicket ? $db->fetchOne("SELECT st.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name FROM support_tickets st LEFT JOIN employees e ON e.id=st.employee_id WHERE st.id=?",[$selTicket]) : null;
$replies   = $selTicket ? $db->fetchAll("SELECT sr.*,u.username FROM support_replies sr LEFT JOIN users u ON u.id=sr.reply_by WHERE sr.ticket_id=? ORDER BY sr.created_at",[$selTicket]) : [];
[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $empOrgClause ORDER BY first_name", $empOrgParams);
$categories = ["Payroll","Attendance","Leave","IT Support","HR Policy","Benefits","Onboarding","Other"];
$priColors  = ["high"=>"var(--pc-red)","medium"=>"var(--pc-amber)","low"=>"var(--pc-green)","urgent"=>"#7c3aed"];

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-ticket me-2"></i>New Ticket</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="new_ticket">
        <?php if(!$user["emp_id"]): ?><div class="mb-2"><label class="pc-label">Employee</label><select name="employee_id" class="form-select form-select-sm"><option value="">Select</option><?php foreach($employees as $e): ?><option value="<?=$e["id"]?>"><?=clean($e["label"])?></option><?php endforeach; ?></select></div><?php endif; ?>
        <div class="mb-2"><label class="pc-label">Category</label><select name="category" class="form-select form-select-sm" required><option value="">Select</option><?php foreach($categories as $c): ?><option value="<?=$c?>"><?=$c?></option><?php endforeach; ?></select></div>
        <div class="mb-2"><label class="pc-label">Subject</label><input type="text" name="subject" class="form-control form-control-sm" required></div>
        <div class="mb-2"><label class="pc-label">Priority</label><select name="priority" class="form-select form-select-sm"><?php foreach(["low","medium","high","urgent"] as $p): ?><option value="<?=$p?>" <?=$p==="medium"?"selected":""?>><?=ucfirst($p)?></option><?php endforeach; ?></select></div>
        <div class="mb-3"><label class="pc-label">Description</label><textarea name="description" class="form-control form-control-sm" rows="3" required></textarea></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-send me-1"></i>Raise Ticket</button>
      </form>
    </div>
    <!-- Filter -->
    <div class="pc-card">
      <div class="pc-card-title">Filter by Status</div>
      <?php foreach(["all"=>"All Tickets","open"=>"Open","in_progress"=>"In Progress","resolved"=>"Resolved","closed"=>"Closed"] as $f=>$l): ?>
      <a href="?filter=<?=$f?>" class="d-block py-1 px-2 rounded mb-1 <?=$filter===$f?"fw-bold":""?>" style="font-size:12.5px;color:<?=$filter===$f?"var(--pc-brand)":"var(--pc-text)"?>;background:<?=$filter===$f?"var(--pc-brand-light)":"transparent"?>"><?=$l?></a>
      <?php endforeach; ?>
    </div>
  </div>

  <div class="col-md-<?=$ticket?"4":"8"?>">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-list me-2"></i>Tickets (<?=count($tickets)?>)</div>
      <?php foreach($tickets as $t): ?>
      <div class="border rounded p-2 mb-2 <?=$selTicket==$t["id"]?"border-primary":""?>" style="cursor:pointer;border-left:3px solid <?=$priColors[$t["priority"]]??"var(--pc-brand)"?> !important" onclick="location='?filter=<?=$filter?>&ticket=<?=$t["id"]?>'"">
        <div class="d-flex justify-content-between">
          <span class="fw-semibold" style="font-size:12.5px"><?=clean($t["subject"])?></span>
          <?=statusBadge($t["status"])?>
        </div>
        <div class="d-flex justify-content-between mt-1" style="font-size:11px;color:var(--pc-text2)">
          <span><code><?=clean($t["ticket_number"])?></code> · <?=clean($t["emp_name"]??"")?></span>
          <span><?=clean($t["category"])?></span>
        </div>
      </div>
      <?php endforeach; if(!$tickets): ?><div class="text-muted text-center py-3 small">No tickets found</div><?php endif; ?>
    </div>
  </div>

  <?php if($ticket): ?>
  <div class="col-md-4">
    <div class="pc-card">
      <div class="d-flex justify-content-between mb-2">
        <div><code class="fw-bold"><?=clean($ticket["ticket_number"])?></code> <?=statusBadge($ticket["status"])?></div>
        <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="close"><input type="hidden" name="id" value="<?=$ticket["id"]?>"><button class="btn btn-xs btn-outline-secondary py-0">Close</button></form>
      </div>
      <div class="fw-semibold mb-1"><?=clean($ticket["subject"])?></div>
      <div class="small text-muted mb-2"><?=clean($ticket["emp_name"])?> · <?=clean($ticket["category"])?> · <?=ucfirst($ticket["priority"])?></div>
      <div class="p-2 rounded mb-3 small" style="background:#f5f8fc"><?=nl2br(clean($ticket["description"]))?></div>
      <!-- Replies -->
      <?php foreach($replies as $r): ?>
      <div class="mb-2 p-2 rounded" style="background:<?=$r["is_staff"]?"var(--pc-brand-light)":"#f5f8fc"?>;font-size:12px">
        <div class="fw-semibold mb-1" style="color:<?=$r["is_staff"]?"var(--pc-brand)":"var(--pc-text)"?>"><?=clean($r["username"])?> <?=$r["is_staff"]?"(Staff)":""?></div>
        <?=nl2br(clean($r["message"]))?>
        <div class="text-muted mt-1" style="font-size:10px"><?=fmtDate($r["created_at"])?></div>
      </div>
      <?php endforeach; ?>
      <!-- Reply form -->
      <?php if($ticket["status"]!=="closed"): ?>
      <form method="POST" class="mt-2">
        <?=csrfField()?><input type="hidden" name="action" value="reply"><input type="hidden" name="ticket_id" value="<?=$ticket["id"]?>">
        <textarea name="message" class="form-control form-control-sm mb-2" rows="2" placeholder="Type reply..." required></textarea>
        <div class="d-flex gap-2">
          <select name="new_status" class="form-select form-select-sm"><?php foreach(["open","in_progress","resolved","closed"] as $s): ?><option value="<?=$s?>" <?=$ticket["status"]===$s?"selected":""?>><?=ucfirst(str_replace("_"," ",$s))?></option><?php endforeach; ?></select>
          <button class="btn btn-pc btn-sm"><i class="ti ti-send"></i></button>
        </div>
      </form>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
</div>
<?php include __DIR__ . "/../../includes/footer.php"; ?>