<?php
// api/my-clients.php — Gestión de clientes para usuarios suscritos (no-admin)
// GET  ?action=list                     → clientes asignados al usuario
// POST action=create  name= url= color= → crear cliente (respeta límite del plan)
// POST action=delete  client_id=        → eliminar cliente propio
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
dm_require_login();

$uid    = (int)dm_user()['id'];
$action = $_GET['action'] ?? ($_POST['action'] ?? '');

if ($action === 'list') {
    $rows = $pdo->prepare("
        SELECT c.id, c.name, c.url, c.color, c.industry, c.services, c.notes, c.created_at
        FROM dm_clients c
        JOIN dm_user_clients uc ON uc.client_id = c.id
        WHERE uc.user_id = ? AND c.active = 1
        ORDER BY c.name
    ");
    $rows->execute([$uid]);
    echo json_encode(['ok' => true, 'clients' => $rows->fetchAll()]);
    exit;
}

if ($action === 'create') {
    dm_csrf_verify();
    dm_check_subscription(true);
    dm_check_client_limit();

    $name  = trim($_POST['name'] ?? '');
    $url   = trim($_POST['url']  ?? '');
    $color = preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['color'] ?? '') ? $_POST['color'] : '#4a9ef8';
    $ind   = trim($_POST['industry'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

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

    $pdo->prepare('INSERT INTO dm_clients (name, industry, url, color, notes, active) VALUES (?,?,?,?,?,1)')
        ->execute([$name, $ind, $url, $color, $notes]);
    $cid = (int)$pdo->lastInsertId();

    // Asociar cliente al usuario
    $pdo->prepare('INSERT IGNORE INTO dm_user_clients (user_id, client_id) VALUES (?,?)')
        ->execute([$uid, $cid]);

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

if ($action === 'delete') {
    dm_csrf_verify();
    $cid = (int)($_POST['client_id'] ?? 0);
    if (!$cid) { echo json_encode(['ok' => false, 'error' => 'client_id requerido']); exit; }

    // Verificar que el cliente pertenece al usuario
    $chk = $pdo->prepare('SELECT 1 FROM dm_user_clients WHERE user_id=? AND client_id=?');
    $chk->execute([$uid, $cid]);
    if (!$chk->fetch()) { http_response_code(403); echo json_encode(['ok' => false, 'error' => 'Sin acceso']); exit; }

    $pdo->prepare('UPDATE dm_clients SET active=0 WHERE id=?')->execute([$cid]);
    $pdo->prepare('DELETE FROM dm_user_clients WHERE user_id=? AND client_id=?')->execute([$uid, $cid]);
    dm_log($uid, $cid, 'delete_client', "Cliente eliminado: {$cid}");
    echo json_encode(['ok' => true]);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Acción no válida']);
