<?php
// Job Card Slips - list and delete only
// Saving is handled by slips/create.php (unified)
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 (!$jobCardId) apiError('Job card ID required.', 422);

try {
    if ($action === 'list') {
        $stmt = $db->prepare("
            SELECT s.*, u.full_name AS captured_by_name
            FROM slips s
            LEFT JOIN users u ON u.id = s.user_id
            WHERE s.job_card_id = ?
            ORDER BY s.slip_date DESC, s.created_at DESC
        ");
        $stmt->execute([$jobCardId]);
        apiSuccess(['slips' => $stmt->fetchAll()]);
    }

    if ($action === 'delete') {
        $id   = (int)post('id');
        $stmt = $db->prepare("SELECT filename FROM slips WHERE id=? AND job_card_id=?");
        $stmt->execute([$id, $jobCardId]);
        $slip = $stmt->fetch();
        if ($slip && $slip['filename']) {
            $path = __DIR__ . '/../../uploads/slips/' . $slip['filename'];
            if (file_exists($path)) unlink($path);
        }
        $db->prepare("DELETE FROM slips WHERE id=? AND job_card_id=?")->execute([$id, $jobCardId]);
        apiSuccess([], 'Deleted.');
    }

    apiError('Unknown action.', 400);
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}
