<?php
/**
 * POST /api/phone-tree.php
 *
 * CRUD consolidat pentru ierarhia Brand → Model → Serie.
 * Body params:
 *   action      = save | delete
 *   level       = brand | model | series
 *   id          = N (0 sau lipsă pentru INSERT)
 *   parent_id   = N (brand_id pentru model, model_id pentru series)
 *   name        = string
 *   notes       = string (opțional)
 *
 * Răspuns: { ok, item: { id, name, ... }, error?: string }
 */
require_once __DIR__ . '/../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['ok' => false, 'error' => 'Doar POST'], 405);
}
if (!csrf_check($_POST['csrf_token'] ?? null)) {
    json_response(['ok' => false, 'error' => 'CSRF invalid'], 403);
}

$action = $_POST['action'] ?? 'save';
$level  = $_POST['level']  ?? '';

$tableMap = [
    'brand'  => ['table' => 'phone_brands', 'parent_col' => null,       'parent_label' => null],
    'model'  => ['table' => 'phone_models', 'parent_col' => 'brand_id', 'parent_label' => 'Brand'],
    'series' => ['table' => 'phone_series', 'parent_col' => 'model_id', 'parent_label' => 'Model'],
];
if (!isset($tableMap[$level])) {
    json_response(['ok' => false, 'error' => 'Level invalid (brand|model|series)'], 422);
}

$table     = $tableMap[$level]['table'];
$parentCol = $tableMap[$level]['parent_col'];
$id        = (int)($_POST['id'] ?? 0);

try {
    // ============ DELETE ============
    if ($action === 'delete') {
        if ($id <= 0) json_response(['ok' => false, 'error' => 'ID lipsă'], 422);
        $affected = db_exec("DELETE FROM $table WHERE id = ?", [$id]);
        json_response(['ok' => true, 'deleted' => $affected]);
    }

    // ============ BULK_SAVE (multiple INSERT) ============
    if ($action === 'bulk_save') {
        $names = $_POST['names'] ?? [];
        if (!is_array($names)) {
            json_response(['ok' => false, 'error' => 'names trebuie să fie array'], 422);
        }
        $parentId = $parentCol ? (int)($_POST['parent_id'] ?? 0) : null;
        if ($parentCol && $parentId <= 0) {
            json_response(['ok' => false, 'error' => $tableMap[$level]['parent_label'] . ' lipsă.'], 422);
        }

        $pdo = db();
        $pdo->beginTransaction();
        $stmt = $parentCol
            ? $pdo->prepare("INSERT INTO $table (name, $parentCol) VALUES (?, ?)")
            : $pdo->prepare("INSERT INTO $table (name) VALUES (?)");

        $added = 0;
        $skipped = 0;
        $createdItems = [];

        try {
            foreach ($names as $rawName) {
                $name = trim((string)$rawName);
                if ($name === '') continue;
                try {
                    if ($parentCol) {
                        $stmt->execute([$name, $parentId]);
                    } else {
                        $stmt->execute([$name]);
                    }
                    $newId = (int)$pdo->lastInsertId();
                    $createdItems[] = ['id' => $newId, 'name' => $name]
                        + ($parentCol ? [$parentCol => $parentId] : []);
                    $added++;
                } catch (PDOException $pe) {
                    if (str_contains($pe->getMessage(), 'UNIQUE')) {
                        $skipped++;
                    } else {
                        throw $pe;
                    }
                }
            }
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }

        // Returnez TOATE rândurile din nivelul respectiv (filtered by parent dacă există)
        // ca să poată frontend-ul să-și actualizeze starea cu noile rânduri.
        $items = $parentCol
            ? db_select("SELECT * FROM $table WHERE $parentCol = ?", [$parentId])
            : db_select("SELECT * FROM $table");

        json_response([
            'ok' => true,
            'added' => $added,
            'skipped' => $skipped,
            'items' => $items,
        ]);
    }

    // ============ SAVE (insert/update) ============
    if ($action === 'save') {
        $name = trim((string)($_POST['name'] ?? ''));
        if ($name === '') {
            json_response(['ok' => false, 'error' => 'Numele este obligatoriu.'], 422);
        }
        $notes = trim((string)($_POST['notes'] ?? '')) ?: null;
        $parentId = $parentCol ? (int)($_POST['parent_id'] ?? 0) : null;
        if ($parentCol && $parentId <= 0) {
            json_response(['ok' => false, 'error' => $tableMap[$level]['parent_label'] . ' lipsă.'], 422);
        }

        if ($id > 0) {
            db_exec("UPDATE $table SET name = ?, notes = ? WHERE id = ?", [$name, $notes, $id]);
            $savedId = $id;
        } else {
            try {
                if ($parentCol) {
                    $savedId = db_exec(
                        "INSERT INTO $table (name, notes, $parentCol) VALUES (?,?,?)",
                        [$name, $notes, $parentId]
                    );
                } else {
                    $savedId = db_exec(
                        "INSERT INTO $table (name, notes) VALUES (?,?)",
                        [$name, $notes]
                    );
                }
            } catch (PDOException $pe) {
                if (str_contains($pe->getMessage(), 'UNIQUE')) {
                    json_response(['ok' => false, 'error' => '„' . $name . '” există deja la acest nivel.'], 409);
                }
                throw $pe;
            }
        }

        $rows = db_select("SELECT * FROM $table WHERE id = ?", [$savedId]);
        json_response(['ok' => true, 'item' => $rows[0] ?? null]);
    }

    json_response(['ok' => false, 'error' => 'Action invalid'], 422);
} catch (Throwable $ex) {
    error_log('[phone-tree] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
