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

function generate_material_code($mysqli) {
  $prefix = 'MAT-' . date('Ym') . '-';
  $like = $prefix . '%';
  $stmt = $mysqli->prepare("SELECT material_code FROM materials WHERE material_code LIKE ? ORDER BY material_code DESC LIMIT 1");
  $stmt->bind_param('s', $like);
  $stmt->execute();
  $res = $stmt->get_result()->fetch_assoc();
  $next = 1;
  if ($res && preg_match('/^(?:MAT-\d{6}-)(\d{4})$/', $res['material_code'], $m)) {
    $next = (int)$m[1] + 1;
  }
  return $prefix . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
}

switch ($action) {
  case 'list':
    $sql = 'SELECT m.id, m.material_code, m.name, pt.name AS type_name, f.name AS finish_name, c.name AS color_name, m.length_mm, m.width_mm, m.thickness_mm, m.is_active
            FROM materials m
            LEFT JOIN product_types pt ON pt.id = m.type_id
            LEFT JOIN finishes f ON f.id = m.finish_id
            LEFT JOIN colors c ON c.id = m.color_id
            ORDER BY m.id';
    $res = $mysqli->query($sql);
    $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, material_code, name, type_id, finish_id, color_id, length_mm, width_mm, thickness_mm, notes, is_active FROM materials 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_material();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $material_code = trim($_POST['material_code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $type_id = !empty($_POST['type_id']) ? (int)$_POST['type_id'] : null;
    $finish_id = !empty($_POST['finish_id']) ? (int)$_POST['finish_id'] : null;
    $color_id = !empty($_POST['color_id']) ? (int)$_POST['color_id'] : null;
    $length_mm = $_POST['length_mm'] !== '' ? (float)$_POST['length_mm'] : null;
    $width_mm = $_POST['width_mm'] !== '' ? (float)$_POST['width_mm'] : null;
    $thickness_mm = $_POST['thickness_mm'] !== '' ? (float)$_POST['thickness_mm'] : null;
    $notes = trim($_POST['notes'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($name === '') json_response(['message' => 'Name required'], 400);
    if ($material_code === '') $material_code = generate_material_code($mysqli);

    $stmt = $mysqli->prepare('INSERT INTO materials (material_code, name, type_id, finish_id, color_id, length_mm, width_mm, thickness_mm, notes, is_active) VALUES (?,?,?,?,?,?,?,?,?,?)');
    $stmt->bind_param('ssiiidddsi', $material_code, $name, $type_id, $finish_id, $color_id, $length_mm, $width_mm, $thickness_mm, $notes, $is_active);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Created']);
    break;

  case 'update':
    ensure_admin_material();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    $material_code = trim($_POST['material_code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $type_id = !empty($_POST['type_id']) ? (int)$_POST['type_id'] : null;
    $finish_id = !empty($_POST['finish_id']) ? (int)$_POST['finish_id'] : null;
    $color_id = !empty($_POST['color_id']) ? (int)$_POST['color_id'] : null;
    $length_mm = $_POST['length_mm'] !== '' ? (float)$_POST['length_mm'] : null;
    $width_mm = $_POST['width_mm'] !== '' ? (float)$_POST['width_mm'] : null;
    $thickness_mm = $_POST['thickness_mm'] !== '' ? (float)$_POST['thickness_mm'] : null;
    $notes = trim($_POST['notes'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if (!$id || $name === '') json_response(['message' => 'Missing fields'], 400);
    $material_code = $material_code !== '' ? $material_code : null;
    $stmt = $mysqli->prepare('UPDATE materials SET material_code=?, name=?, type_id=?, finish_id=?, color_id=?, length_mm=?, width_mm=?, thickness_mm=?, notes=?, is_active=? WHERE id=?');
    $stmt->bind_param('ssiiidddsii', $material_code, $name, $type_id, $finish_id, $color_id, $length_mm, $width_mm, $thickness_mm, $notes, $is_active, $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Updated']);
    break;

  case 'delete':
    ensure_admin_material();
    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 materials WHERE id = ?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Deleted']);
    break;

  case 'generate_code':
    ensure_admin_material();
    $code = generate_material_code($mysqli);
    json_response(['code' => $code]);
    break;

  case 'list_types':
    $rows = [];
    $res = $mysqli->query('SELECT id, name FROM product_types ORDER BY name');
    while ($r = $res->fetch_assoc()) { $rows[] = $r; }
    json_response(['data' => $rows]);
    break;

  case 'list_finishes':
    $rows = [];
    $res = $mysqli->query('SELECT id, name FROM finishes ORDER BY name');
    while ($r = $res->fetch_assoc()) { $rows[] = $r; }
    json_response(['data' => $rows]);
    break;

  case 'list_colors':
    $rows = [];
    $res = $mysqli->query('SELECT id, name FROM colors ORDER BY name');
    while ($r = $res->fetch_assoc()) { $rows[] = $r; }
    json_response(['data' => $rows]);
    break;

  case 'add_type':
    ensure_admin_material();
    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', 'id' => $mysqli->insert_id]);
    break;

  case 'add_finish':
    ensure_admin_material();
    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 finishes (name) VALUES (?)');
    $stmt->bind_param('s', $name);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Created', 'id' => $mysqli->insert_id]);
    break;

  case 'add_color':
    ensure_admin_material();
    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 colors (name) VALUES (?)');
    $stmt->bind_param('s', $name);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Created', 'id' => $mysqli->insert_id]);
    break;

  default:
    json_response(['message' => 'Invalid action'], 400);
}
