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

$action    = post('action', 'get');
$jobCardId = (int)post('job_card_id', 0);
if (!$jobCardId) apiError('Job card ID required.', 422);

if ($action === 'get') {
    try {
        $stmt = $db->prepare("
            SELECT r.*, u.full_name AS submitted_by_name
            FROM job_card_reports r
            LEFT JOIN users u ON u.id = r.submitted_by
            WHERE r.job_card_id=?
        ");
        $stmt->execute([$jobCardId]);
        $report = $stmt->fetch();
        // Don't send full signature data in list — just flag
        if ($report) { $report['has_signature'] = !empty($report['signature_data']); unset($report['signature_data']); }

        $clStmt = $db->prepare("SELECT COUNT(*) AS total, SUM(is_checked) AS done FROM job_card_checklist WHERE job_card_id=?");
        $clStmt->execute([$jobCardId]); $cl = $clStmt->fetch();

        $plStmt = $db->prepare("SELECT COUNT(*) AS total, SUM(is_checked) AS done FROM job_card_planning WHERE job_card_id=?");
        $plStmt->execute([$jobCardId]); $pl = $plStmt->fetch();

        apiSuccess([
            'report'          => $report ?: null,
            'checklist_total' => (int)$cl['total'],
            'checklist_done'  => (int)($cl['done'] ?? 0),
            'planning_total'  => (int)$pl['total'],
            'planning_done'   => (int)($pl['done'] ?? 0),
        ]);
    } catch (Exception $e) { apiError('DB error: ' . $e->getMessage(), 500); }
}

// save
$work      = trim(post('work_performed', ''));
$clientSig = post('client_name_signed', '');
if (!$work)      apiError('Work performed is required.', 422);
if (!$clientSig) apiError('Client name/sign-off is required.', 422);

try {
    $sigData = post('signature_data', '');

    $db->prepare("
        INSERT INTO job_card_reports
            (job_card_id, work_performed, materials_used, issues_found, recommendations,
             client_name_signed, client_satisfied, signature_data, submitted_by)
        VALUES (?,?,?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE
            work_performed=VALUES(work_performed), materials_used=VALUES(materials_used),
            issues_found=VALUES(issues_found), recommendations=VALUES(recommendations),
            client_name_signed=VALUES(client_name_signed), client_satisfied=VALUES(client_satisfied),
            signature_data=VALUES(signature_data), submitted_by=VALUES(submitted_by), submitted_at=NOW()
    ")->execute([
        $jobCardId, $work,
        post('materials_used'), post('issues_found'), post('recommendations'),
        $clientSig, post('client_satisfied') ? 1 : 0,
        $sigData ?: null,
        $user['id'],
    ]);

    apiSuccess([], 'Report submitted. Client signature captured.');
} catch (Exception $e) { apiError('DB error: ' . $e->getMessage(), 500); }