<?php
require_once __DIR__ . '/../auth.php';
dm_require_login();
header('Content-Type: application/json');

dm_csrf_verify();

$user    = dm_user();
$uid     = (int)$user['id'];
$is_adm  = dm_is_admin();
$sub     = function_exists('dm_get_subscription') ? dm_get_subscription($uid) : null;
$max_c   = $sub['max_clients'] ?? ($is_adm ? 999 : 0);
$action  = $_POST['action'] ?? '';

if ($action === 'create_client') {
    $name     = trim($_POST['name'] ?? '');
    $industry = trim($_POST['industry'] ?? '');
    $url      = trim($_POST['url'] ?? '');
    $services = implode(',', array_intersect(
        explode(',', $_POST['services'] ?? ''),
        ['meta','google','tiktok','seo','email','web','shopify']
    ));

    if (!$name) { echo json_encode(['ok'=>false,'error'=>'El nombre es obligatorio.']); exit; }

    // Check plan limit for non-admin
    if (!$is_adm) {
        if ($max_c <= 0) {
            echo json_encode(['ok'=>false,'error'=>'Tu plan no permite agregar clientes. Actualiza tu suscripción.']);
            exit;
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM dm_clients c JOIN dm_user_clients uc ON uc.client_id=c.id WHERE uc.user_id=?");
        $stmt->execute([$uid]);
        $cur = (int)$stmt->fetchColumn();
        if ($cur >= $max_c) {
            echo json_encode(['ok'=>false,'error'=>"Límite del plan alcanzado ({$max_c} clientes). Actualiza tu plan para agregar más."]);
            exit;
        }
    }

    $pdo->prepare('INSERT INTO dm_clients (name,industry,url,color,services,contact_email) VALUES (?,?,?,?,?,?)')
        ->execute([$name, $industry, $url, '#4a9ef8', $services, '']);
    $new_cid = (int)$pdo->lastInsertId();

    if (!$is_adm) {
        $pdo->prepare('INSERT IGNORE INTO dm_user_clients (user_id,client_id) VALUES (?,?)')->execute([$uid, $new_cid]);
    }

    dm_log($uid, $new_cid, 'create_client', "Cliente creado: {$name}");
    echo json_encode(['ok'=>true,'client_id'=>$new_cid,'name'=>$name]);
    exit;
}

echo json_encode(['ok'=>false,'error'=>'Acción no reconocida.']);
