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

function ensure_services_table(mysqli $db){
  $db->query("CREATE TABLE IF NOT EXISTS services (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    description VARCHAR(255) NULL,
    default_rate DECIMAL(12,2) NOT NULL DEFAULT 0,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB");
}

ensure_services_table($mysqli);

switch ($action) {
  case 'list': {
    $only_active = isset($_GET['active']) ? (int)$_GET['active'] : null;
    $sql = 'SELECT id, name, description, default_rate, is_active FROM services';
    $params = [];
    $types = '';
    $where = [];
    if ($only_active === 1) { $where[] = 'is_active=1'; }
    if ($where) { $sql .= ' WHERE ' . implode(' AND ', $where); }
    $sql .= ' ORDER BY name ASC';

    $stmt = $mysqli->prepare($sql);
    if (!$stmt) json_response(['message'=>'SQL prepare failed (services.list): '.$mysqli->error], 500);
    if ($types) { $stmt->bind_param($types, ...$params); }
    $stmt->execute();
    $res = $stmt->get_result();
    $rows = [];
    while($r=$res->fetch_assoc()){ $rows[] = $r; }
    json_response(['data'=>$rows]);
    break; }

  case 'create': {
    ensure_admin_services();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $rate = isset($_POST['default_rate']) ? (float)$_POST['default_rate'] : 0.0;
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
    if ($name === '') json_response(['message'=>'Name is required'], 400);

    $stmt = $mysqli->prepare('INSERT INTO services (name, description, default_rate, is_active) VALUES (?,?,?,?)');
    $descVal = ($description === '') ? null : $description;
    $stmt->bind_param('ssdi', $name, $descVal, $rate, $is_active);
    if (!$stmt->execute()) json_response(['message'=>$stmt->error], 500);
    json_response(['message'=>'Created', 'id'=>$mysqli->insert_id]);
    break; }

  case 'update': {
    ensure_admin_services();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $rate = isset($_POST['default_rate']) ? (float)$_POST['default_rate'] : 0.0;
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
    if (!$id) json_response(['message'=>'Missing id'], 400);
    if ($name === '') json_response(['message'=>'Name is required'], 400);

    $stmt = $mysqli->prepare('UPDATE services SET name=?, description=?, default_rate=?, is_active=? WHERE id=?');
    $descVal = ($description === '') ? null : $description;
    $stmt->bind_param('ssdii', $name, $descVal, $rate, $is_active, $id);
    if (!$stmt->execute()) json_response(['message'=>$stmt->error], 500);
    json_response(['message'=>'Updated']);
    break; }

  case 'delete': {
    ensure_admin_services();
    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 services 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);
}
