<?php
// ============================================================
//  ajax/save_keywords.php
//  Saves selected keyword IDs for a submission
//  Replaces entire set (delete + re-insert)
// ============================================================
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

$submissionId = (int)($_POST['submission_id'] ?? 0);
$keywordIds   = json_decode($_POST['keyword_ids'] ?? '[]', true);

if (!$submissionId) jsonResponse(false, 'Submission ID required');
if (!is_array($keywordIds)) jsonResponse(false, 'Invalid keyword_ids format');

// Sanitize: integers only, max 8
$keywordIds = array_slice(
    array_unique(array_filter(array_map('intval', $keywordIds))),
    0, 8
);

// Verify ownership
$stmt = db()->prepare("SELECT submission_id FROM submissions WHERE submission_id = ? AND user_id = ?");
$stmt->execute([$submissionId, $user_id]);
if (!$stmt->fetch()) jsonResponse(false, 'Access denied');

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

    // Delete existing
    $db->prepare("DELETE FROM submission_keywords WHERE submission_id = ?")
       ->execute([$submissionId]);

    // Re-insert in order
    if ($keywordIds) {
        $stmt = $db->prepare(
            "INSERT INTO submission_keywords (submission_id, keyword_id, display_order)
             VALUES (?, ?, ?)"
        );
        foreach ($keywordIds as $order => $kwId) {
            $stmt->execute([$submissionId, $kwId, $order + 1]);
        }
    }

    $db->commit();

    jsonResponse(true, 'Keywords saved', [
        'count'       => count($keywordIds),
        'keyword_ids' => $keywordIds,
    ]);

} catch (PDOException $e) {
    $db->rollBack();
    jsonResponse(false, 'DB error: ' . $e->getMessage());
}