<?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_types() {
  if (!has_role(['admin','super_admin'])) { json_response(['message' => 'Forbidden'], 403); }
}

switch ($action) {
  case 'list':
    $res = $mysqli->query('SELECT id, name FROM product_types ORDER BY name');
    $data = [];
    while ($row = $res->fetch_assoc()) { $data[] = $row; }
    json_response(['data' => $data]);
    break;
  case 'get':
    $id = (int)($_GET['id'] ?? 0);
    $stmt = $mysqli->prepare('SELECT id, name FROM product_types 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_types();
    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 product_types (name) VALUES (?)');
    $stmt->bind_param('s', $name);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Created']);
    break;
  case 'update':
    ensure_admin_types();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    if (!$id || $name === '') json_response(['message' => 'Missing fields'], 400);
    $stmt = $mysqli->prepare('UPDATE product_types SET name=? WHERE id=?');
    $stmt->bind_param('si', $name, $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Updated']);
    break;
  case 'delete':
    ensure_admin_types();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) json_response(['message' => 'Missing id'], 400);
    $stmt = $mysqli->prepare('DELETE FROM product_types WHERE id = ?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Deleted']);
    break;
  default:
    json_response(['message' => 'Invalid action'], 400);
}
