<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');
$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

function ensure_admin_designation(){ if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403); }

// Ensure table exists (id, name unique, is_active)
$mysqli->query("CREATE TABLE IF NOT EXISTS designations (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL UNIQUE,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB");

switch ($action) {
  case 'list':
    $onlyActive = isset($_GET['only_active']) ? (int)$_GET['only_active'] : 0;
    $sql = 'SELECT id, name, is_active FROM designations';
    if ($onlyActive) { $sql .= ' WHERE is_active=1'; }
    $sql .= ' ORDER BY name';
    $res = $mysqli->query($sql);
    $rows=[]; while($r=$res->fetch_assoc()) $rows[]=$r;
    json_response(['data'=>$rows]);
    break;
  case 'get':
    $id=(int)($_GET['id']??0); if(!$id) json_response(['message'=>'ID required'], 422);
    $stmt=$mysqli->prepare('SELECT id, name, is_active FROM designations WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $row=$stmt->get_result()->fetch_assoc();
    if (!$row) json_response(['message'=>'Not found'],404);
    json_response(['data'=>$row]);
    break;
  case 'create':
    ensure_admin_designation(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $name = trim($_POST['name'] ?? ''); if ($name==='') json_response(['message'=>'Name required'], 400);
    $stmt=$mysqli->prepare('INSERT INTO designations(name,is_active) VALUES (?,1)');
    $stmt->bind_param('s', $name);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error], 400);
    json_response(['id'=>$stmt->insert_id]);
    break;
  case 'update':
    ensure_admin_designation(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id']??0); if(!$id) json_response(['message'=>'ID required'],422);
    $name = trim($_POST['name'] ?? ''); if ($name==='') json_response(['message'=>'Name required'], 400);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $stmt=$mysqli->prepare('UPDATE designations SET name=?, is_active=? WHERE id=?');
    $stmt->bind_param('sii', $name, $is_active, $id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error], 400);
    json_response(['ok'=>true]);
    break;
  case 'delete':
    ensure_admin_designation(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id=(int)($_POST['id']??0); if(!$id) json_response(['message'=>'ID required'],422);
    $stmt=$mysqli->prepare('DELETE FROM designations WHERE id=?');
    $stmt->bind_param('i',$id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error], 400);
    json_response(['ok'=>true]);
    break;
  default:
    json_response(['message'=>'Invalid action'],400);
}
