<?php
/**
 * POST /api/save-phone-link.php
 *
 * Body:
 *   product_id        = N
 *   primary_series_id = N (sau gol pentru a deconecta)
 *   secondary_ids[]   = array de phone_series_id (modele compatibile)
 *
 * Acțiune:
 *   1. Setează products.phone_series_id = primary_series_id
 *   2. Șterge toate rândurile din product_phone_series_alt pentru acest produs
 *   3. Reinserează un rând pentru fiecare secondary_id (exclus primary)
 *
 * Răspuns: { ok, primary: {id,brand,model,series}|null, secondaries: [...] }
 */
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);
}

$productId = (int)($_POST['product_id'] ?? 0);
$primaryId = !empty($_POST['primary_series_id']) ? (int)$_POST['primary_series_id'] : null;
$secondaryRaw = $_POST['secondary_ids'] ?? [];

if ($productId <= 0) {
    json_response(['ok' => false, 'error' => 'product_id invalid'], 422);
}
if (!is_array($secondaryRaw)) {
    json_response(['ok' => false, 'error' => 'secondary_ids trebuie array'], 422);
}

$secondaryIds = array_values(array_unique(array_filter(
    array_map('intval', $secondaryRaw),
    fn($v) => $v > 0 && $v !== $primaryId
)));

try {
    $pdo = db();
    $pdo->beginTransaction();

    db_exec("UPDATE products SET phone_series_id = ? WHERE id = ?", [$primaryId, $productId]);
    db_exec("DELETE FROM product_phone_series_alt WHERE product_id = ?", [$productId]);

    if ($secondaryIds) {
        $stmt = $pdo->prepare("INSERT INTO product_phone_series_alt (product_id, phone_series_id) VALUES (?, ?)");
        foreach ($secondaryIds as $sid) {
            $stmt->execute([$productId, $sid]);
        }
    }

    $pdo->commit();

    // Returnez datele complete pentru frontend
    $primary = null;
    if ($primaryId) {
        $rows = db_select(
            "SELECT ps.id, pb.name AS brand_name, pm.name AS model_name, ps.name AS series_name
             FROM phone_series ps
             JOIN phone_models pm ON pm.id = ps.model_id
             JOIN phone_brands pb ON pb.id = pm.brand_id
             WHERE ps.id = ?",
            [$primaryId]
        );
        if ($rows) $primary = $rows[0];
    }

    $secondaries = [];
    if ($secondaryIds) {
        $ph = implode(',', array_fill(0, count($secondaryIds), '?'));
        $secondaries = db_select(
            "SELECT ps.id, pb.name AS brand_name, pm.name AS model_name, ps.name AS series_name
             FROM phone_series ps
             JOIN phone_models pm ON pm.id = ps.model_id
             JOIN phone_brands pb ON pb.id = pm.brand_id
             WHERE ps.id IN ($ph)",
            $secondaryIds
        );
    }

    json_response([
        'ok'           => true,
        'primary'      => $primary,
        'secondaries'  => $secondaries,
        'alt_ids'      => $secondaryIds,
    ]);
} catch (Throwable $ex) {
    if (db()->inTransaction()) db()->rollBack();
    error_log('[save-phone-link] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
