<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
header('Content-Type: application/json; charset=utf-8');

$uid = (int)($_SESSION['user_id'] ?? 0);
if ($uid <= 0) { echo json_encode(['success'=>false,'error'=>'auth']); exit; }

try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  $client_id = (int)($_POST['client_id'] ?? $_GET['client_id'] ?? 0);
  $new_status = trim((string)($_POST['status'] ?? $_GET['status'] ?? ''));
  $desk_id = (int)($_POST['desk_id'] ?? $_GET['desk_id'] ?? 0);
  if ($client_id <= 0 || $new_status === '') { echo json_encode(['success'=>false,'error'=>'input']); exit; }
  $stCtx = $pdo->prepare('SELECT id, lead_id, desk_id FROM clients WHERE id = ?');
  $stCtx->execute([$client_id]);
  $ctx = $stCtx->fetch(PDO::FETCH_ASSOC) ?: [];
  if (!$ctx) { echo json_encode(['success'=>false,'error'=>'not_found']); exit; }
  $desk = $desk_id > 0 ? $desk_id : (int)($ctx['desk_id'] ?? 0);
  $allowed = true;
  if ($desk > 0) {
    try {
      $stA = $pdo->prepare('SELECT 1 FROM desk_allowed_statuses WHERE desk_id = ? AND status = ? LIMIT 1');
      $stA->execute([$desk, $new_status]);
      $allowed = (bool)$stA->fetchColumn();
    } catch (Throwable $__) { $allowed = true; }
  }
  if (!$allowed) { echo json_encode(['success'=>false,'error'=>'not_allowed']); exit; }
  // ensure column
  try { $pdo->query("SHOW COLUMNS FROM clients LIKE 'desk_status'"); }
  catch (Throwable $__) { $pdo->exec("ALTER TABLE clients ADD COLUMN desk_status VARCHAR(64) NULL"); }
  $pdo->prepare('UPDATE clients SET desk_status = ?, updated_at = NOW() WHERE id = ?')->execute([$new_status, $client_id]);
  $leadId = (int)($ctx['lead_id'] ?? 0);
  if ($leadId > 0) { try { $pdo->prepare('UPDATE leads SET status = ?, updated_at = NOW() WHERE id = ?')->execute([$new_status, $leadId]); } catch (Throwable $__) {} }
  echo json_encode(['success'=>true,'status'=>$new_status,'client_id'=>$client_id]);
} catch (Throwable $e) { echo json_encode(['success'=>false,'error'=>'server']); }
?>
