<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireAuth();
$db   = getDB();

$action    = post('action', 'list');
$jobCardId = (int)post('job_card_id', 0);

if ($action === 'list') {
    $stmt = $db->prepare("SELECT * FROM job_card_planning WHERE job_card_id=? ORDER BY sort_order, id");
    $stmt->execute([$jobCardId]);
    apiSuccess(['items' => $stmt->fetchAll()]);
}

if ($action === 'delete') {
    $db->prepare("DELETE FROM job_card_planning WHERE id=? AND job_card_id=?")->execute([(int)post('id'), $jobCardId]);
    apiSuccess([], 'Removed.');
}

if ($action === 'check') {
    $id        = (int)post('id', 0);
    $checked   = post('is_checked') ? 1 : 0;
    $db->prepare("UPDATE job_card_planning SET is_checked=? WHERE id=? AND job_card_id=?")->execute([$checked, $id, $jobCardId]);
    apiSuccess(['is_checked' => $checked]);
}

if ($action === 'reorder') {
    $ids = post('ids', []);
    foreach ($ids as $order => $id) {
        $db->prepare("UPDATE job_card_planning SET sort_order=? WHERE id=?")->execute([$order, (int)$id]);
    }
    apiSuccess([], 'Reordered.');
}

// add
$item = trim(post('item', ''));
if (!$item)      apiError('Item text required.', 422);
if (!$jobCardId) apiError('Job card ID required.', 422);

$db->prepare("INSERT INTO job_card_planning (job_card_id,item,item_type,sort_order,created_by) VALUES (?,?,?,?,?)")
   ->execute([$jobCardId, $item, post('item_type','task'), post('sort_order',0), $user['id']]);
apiSuccess(['id' => (int)$db->lastInsertId()], 'Item added.', 201);
