<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'Unauthorized'])); }
require_once '../connect.php';
$account_id = $_SESSION['account_id'];
$raw    = file_get_contents('php://input');
$json   = $raw ? json_decode($raw, true) : null;
$action = $_POST['action'] ?? ($json['action'] ?? '');

switch ($action) {
  case 'add':
    requirePermission($conn, 'settings', 'tab_stages');
    $name     = sanitize($conn, $_POST['name'] ?? '');
    $color    = sanitize($conn, $_POST['color'] ?? '#00e5c3');
    $position = (int)($_POST['position'] ?? 99);
    $is_start = isset($_POST['is_start']) ? 1 : 0;
    $is_end   = isset($_POST['is_end']) ? 1 : 0;
    if (!$name) jsonResponse(false, 'Stage name required');
    $conn->query("INSERT INTO stage (name, color, position, is_start, is_end, account_id) VALUES ('$name','$color',$position,$is_start,$is_end,$account_id)");
    jsonResponse(true, 'Stage added', ['id' => $conn->insert_id]);
  case 'delete':
    requirePermission($conn, 'settings', 'tab_stages');
    $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
    // Check if any leads use this stage
    $chk = $conn->query("SELECT COUNT(*) as cnt FROM leads WHERE stage_id=$id");
    $cnt = $chk->fetch_assoc()['cnt'];
    if ($cnt > 0) jsonResponse(false, "Cannot delete: $cnt lead(s) use this stage");
    $conn->query("DELETE FROM stage WHERE id=$id AND account_id=$account_id");
    jsonResponse(true, 'Stage deleted');
  default:
    jsonResponse(false, 'Invalid action');
}
