<?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_checklist 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_checklist 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;
    if ($checked) {
        $db->prepare("UPDATE job_card_checklist SET is_checked=1, checked_by=?, checked_at=NOW() WHERE id=? AND job_card_id=?")
           ->execute([$user['id'], $id, $jobCardId]);
    } else {
        $db->prepare("UPDATE job_card_checklist SET is_checked=0, checked_by=NULL, checked_at=NULL WHERE id=? AND job_card_id=?")
           ->execute([$id, $jobCardId]);
    }
    apiSuccess(['is_checked' => $checked]);
}

// add item
$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_checklist (job_card_id,item,sort_order,created_by) VALUES (?,?,?,?)")
   ->execute([$jobCardId, $item, post('sort_order',0), $user['id']]);
apiSuccess(['id' => (int)$db->lastInsertId()], 'Item added.', 201);
