<?php
require_once __DIR__ . '/config.php';
require_auth();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(['error' => 'Method not allowed'], 405);
}

$db = get_db();
$input = json_input();

$action = $input['action'] ?? '';
$rowIds = $input['row_ids'] ?? [];

if (!is_array($rowIds) || count($rowIds) === 0) {
    respond(['error' => 'row_ids must be a non-empty array'], 422);
}

$validActions = ['onboard', 'discard', 'set_active', 'set_inactive', 'set_discontinued'];
if (!in_array($action, $validActions, true)) {
    respond(['error' => 'Invalid action'], 422);
}

$statusMap = [
    'onboard' => 'onboarded',
    'discard' => 'discarded',
    'set_active' => 'onboarded',
    'set_inactive' => 'onboarded',
    'set_discontinued' => 'onboarded',
];

$placeholders = implode(',', array_fill(0, count($rowIds), '?'));
$stmt = $db->prepare("UPDATE import_rows SET row_status = ? WHERE id IN ($placeholders)");
$stmt->execute([$statusMap[$action], ...$rowIds]);

// If the action implies a style-status change, and the row corresponds to
// an existing style (matched by style_code), update that style's status.
if (in_array($action, ['set_active', 'set_inactive', 'set_discontinued'], true)) {
    $newStyleStatus = [
        'set_active' => 'Active',
        'set_inactive' => 'Inactive',
        'set_discontinued' => 'Discontinued',
    ][$action];

    $placeholders2 = implode(',', array_fill(0, count($rowIds), '?'));
    $rows = $db->prepare("SELECT style_code FROM import_rows WHERE id IN ($placeholders2)");
    $rows->execute($rowIds);
    $styleCodes = array_column($rows->fetchAll(), 'style_code');

    if (count($styleCodes) > 0) {
        $codePlaceholders = implode(',', array_fill(0, count($styleCodes), '?'));
        $upd = $db->prepare("UPDATE styles SET status = ? WHERE style_code IN ($codePlaceholders)");
        $upd->execute([$newStyleStatus, ...$styleCodes]);
    }
}

respond(['ok' => true, 'affected' => count($rowIds), 'action' => $action]);
