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

requireRole([1, 5]); // Admin and Dev only
$db = getDB();
$id = (int)post('id', 0);
if (!$id) apiError('Job card ID required.', 422);

// Verify exists
$jc = $db->prepare("SELECT id, job_number FROM job_cards WHERE id=?");
$jc->execute([$id]);
if (!$jc->fetch()) apiError('Job card not found.', 404);

// Delete in correct order (FK constraints)
$tables = [
    'job_card_time_logs',
    'job_card_notes',
    'job_card_images',
    'job_card_locations',
    'job_card_planning',
    'job_card_checklist',
    'job_card_technicians',
    'job_card_reports',
    'job_card_slips',
];

foreach ($tables as $table) {
    try {
        $db->prepare("DELETE FROM {$table} WHERE job_card_id=?")->execute([$id]);
    } catch (Exception $e) {
        // Table may not exist or column may differ — continue
    }
}

$db->prepare("DELETE FROM job_cards WHERE id=?")->execute([$id]);

apiSuccess([], 'Job card deleted.');