<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user      = requireRole([1, 2]);
$db        = getDB();
$action    = post('action', 'add'); // add | remove | list
$jobCardId = (int)post('job_card_id', 0);
if (!$jobCardId) apiError('Job card ID required.', 422);

if ($action === 'list') {
    $s = $db->prepare("SELECT jct.*, u.full_name, u.email FROM job_card_technicians jct JOIN users u ON u.id = jct.user_id WHERE jct.job_card_id=?");
    $s->execute([$jobCardId]);
    apiSuccess(['technicians' => $s->fetchAll()]);
}
if ($action === 'remove') {
    $db->prepare("DELETE FROM job_card_technicians WHERE job_card_id=? AND user_id=?")->execute([$jobCardId, (int)post('user_id')]);
    apiSuccess([], 'Removed.');
}
// add
$userId = (int)post('user_id', 0);
if (!$userId) apiError('User ID required.', 422);
$db->prepare("INSERT IGNORE INTO job_card_technicians (job_card_id, user_id, role) VALUES (?,?,?)")
   ->execute([$jobCardId, $userId, post('role','technician')]);
// Also set assigned_to if this is the first/lead
if (post('set_lead')) {
    $db->prepare("UPDATE job_cards SET assigned_to=? WHERE id=?")->execute([$userId, $jobCardId]);
}
apiSuccess([], 'Technician added.');
