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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    // FIX (07 Jul 2026): this had no role check at all — any logged-in
    // employee could post/edit/delete company-wide notices. Also added
    // company_id (migration_notice_board_company.sql) and scoped
    // everything to the current org.
    requireRole('superadmin','admin','hr','management');
    $orgCompanies = orgCompanyIds($db);
    $companyId    = $orgCompanies[0] ?? 0;
    $action = $_POST["action"] ?? "";
    if ($action === "save") {
        $id = postInt("id");
        if ($id) {
            $owned = $db->fetchOne("SELECT id FROM notice_board WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([$id], $orgCompanies));
            if (!$owned) { setFlash('error','Notice not found.'); header("Location: ".BASE_URL."/modules/notice/index.php"); exit; }
            $db->execute("UPDATE notice_board SET title=?,category=?,content=?,priority=?,visible_to=?,expiry_date=?,is_active=? WHERE id=?",
                [post("title"),post("category"),post("content"),post("priority"),post("visible_to"),post("expiry")?:null,postInt("is_active"),$id]);
        } else {
            $db->execute("INSERT INTO notice_board (company_id,title,category,content,priority,visible_to,expiry_date,is_active,created_by) VALUES (?,?,?,?,?,?,?,?,?)",
                [$companyId,post("title"),post("category"),post("content"),post("priority"),post("visible_to"),post("expiry")?:null,1,$user["id"]]);
        }
        setFlash("success","Notice saved.");
    } elseif ($action === "delete") {
        $owned = $db->fetchOne("SELECT id FROM notice_board WHERE id=? AND company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")", array_merge([postInt("id")], $orgCompanies));
        if ($owned) {
            $db->execute("DELETE FROM notice_board WHERE id=?",[postInt("id")]);
            setFlash("success","Notice deleted.");
        } else {
            setFlash("error","Notice not found.");
        }
    }
    header("Location: ".BASE_URL."/modules/notice/index.php"); exit;
}

// FIX: scope to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'n.company_id');
$editId   = cleanInt($_GET["edit"] ?? 0);
$edit     = $editId ? $db->fetchOne("SELECT * FROM notice_board WHERE id=? AND $orgClause", array_merge([$editId], $orgParams)) : null;
$notices  = $db->fetchAll("SELECT n.*,u.username AS posted_by FROM notice_board n LEFT JOIN users u ON u.id=n.created_by WHERE n.is_active=1 AND (n.expiry_date IS NULL OR n.expiry_date >= CURDATE()) AND $orgClause ORDER BY n.priority DESC,n.created_at DESC", $orgParams);
$archived = $db->fetchAll("SELECT n.*,u.username AS posted_by FROM notice_board n LEFT JOIN users u ON u.id=n.created_by WHERE (n.is_active=0 OR (n.expiry_date IS NOT NULL AND n.expiry_date < CURDATE())) AND $orgClause ORDER BY n.created_at DESC LIMIT 20", $orgParams);
$priColors= ["high"=>"var(--pc-red)","medium"=>"var(--pc-amber)","low"=>"var(--pc-green)"];
$priBg    = ["high"=>"var(--pc-red-bg)","medium"=>"var(--pc-amber-bg)","low"=>"var(--pc-green-bg)"];

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-bell-plus me-2"></i><?=$edit?"Edit":"New"?> Notice</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save">
        <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit["id"]?>"><?php endif; ?>
        <div class="mb-2"><label class="pc-label">Title</label><input type="text" name="title" class="form-control form-control-sm" value="<?=clean($edit["title"]??"")?>" required></div>
        <div class="mb-2"><label class="pc-label">Category</label>
          <select name="category" class="form-select form-select-sm">
            <?php foreach(["General","Policy","Holiday","Event","Urgent","Payroll","HR","IT"] as $c): ?>
            <option value="<?=$c?>" <?=($edit["category"]??"")===$c?"selected":""?>><?=$c?></option>
            <?php endforeach; ?>
          </select></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"] as $p): ?><option value="<?=$p?>" <?=($edit["priority"]??"")===$p?"selected":""?>><?=ucfirst($p)?></option><?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Visible To</label>
          <select name="visible_to" class="form-select form-select-sm">
            <?php foreach(["all"=>"All Employees","hr"=>"HR Only","admin"=>"Admin Only","management"=>"Management"] as $v=>$l): ?>
            <option value="<?=$v?>" <?=($edit["visible_to"]??"")===$v?"selected":""?>><?=$l?></option>
            <?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Expiry Date (optional)</label><input type="date" name="expiry" class="form-control form-control-sm" value="<?=$edit["expiry_date"]??''?>"></div>
        <div class="mb-3"><label class="pc-label">Content</label><textarea name="content" class="form-control form-control-sm" rows="4" required><?=clean($edit["content"]??"")?></textarea></div>
        <div class="mb-3 form-check"><input type="checkbox" name="is_active" value="1" class="form-check-input" id="ia" <?=($edit["is_active"]??1)?"checked":""?>><label class="form-check-label small" for="ia">Active</label></div>
        <div class="d-flex gap-2"><button class="btn btn-pc btn-sm flex-fill">Publish Notice</button><?php if($edit): ?><a href="?" class="btn btn-outline-secondary btn-sm">Cancel</a><?php endif; ?></div>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-bell me-2"></i>Active Notices (<?=count($notices)?>)</div>
      <?php if($notices): ?>
      <?php foreach($notices as $n): ?>
      <div class="border rounded p-3 mb-2" style="border-left:4px solid <?=$priColors[$n["priority"]]??"var(--pc-brand)"?> !important;background:<?=$priBg[$n["priority"]]??"var(--pc-brand-light)"?>">
        <div class="d-flex justify-content-between align-items-start mb-1">
          <div>
            <span class="fw-bold"><?=clean($n["title"])?></span>
            <span class="badge ms-1" style="font-size:9px;background:var(--pc-brand-light);color:var(--pc-brand)"><?=clean($n["category"])?></span>
            <span class="badge ms-1" style="font-size:9px;background:<?=$priBg[$n["priority"]]??"#fff"?>;color:<?=$priColors[$n["priority"]]??"var(--pc-brand)"?>"><?=ucfirst($n["priority"])?></span>
          </div>
          <div class="d-flex gap-1">
            <a href="?edit=<?=$n["id"]?>" class="btn btn-xs btn-outline-primary py-0 px-1">Edit</a>
            <form method="POST" class="d-inline" onsubmit="return confirm('Delete?')">
              <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$n["id"]?>">
              <button class="btn btn-xs btn-outline-danger py-0 px-1">Del</button>
            </form>
          </div>
        </div>
        <p class="mb-1 small"><?=clean($n["content"])?></p>
        <div class="text-muted" style="font-size:10px">Posted by: <?=clean($n["posted_by"])?> · <?=fmtDate($n["created_at"])?><?=$n["expiry_date"]?" · Expires: ".fmtDate($n["expiry_date"]):""?></div>
      </div>
      <?php endforeach; ?>
      <?php else: ?><div class="text-muted text-center py-3">No active notices</div><?php endif; ?>
    </div>
    <?php if($archived): ?>
    <div class="pc-card">
      <div class="pc-card-title text-muted"><i class="ti ti-archive me-2"></i>Archived Notices</div>
      <?php foreach($archived as $n): ?>
      <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:12px;opacity:0.7">
        <div><span class="fw-semibold"><?=clean($n["title"])?></span> <span class="badge" style="font-size:9px;background:#f3f4f6;color:#6b7280"><?=clean($n["category"])?></span></div>
        <span class="text-muted"><?=fmtDate($n["created_at"])?></span>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . "/../../includes/footer.php"; ?>