<?php
// ============================================================
// GenericLabForm
// Backward-compatible handler for all labs without a
// specific implementation. Uses the existing lab_work_forms table.
// ============================================================
class GenericLabForm implements ILabForm {

    public function getTableSchema(): string {
        return ''; // Table already exists from original schema
    }

    public function validate(array $post): array {
        $errors = [];
        if (empty($post['place_of_test'])) $errors[] = 'Place of test is required.';
        return $errors;
    }

    public function save(int $requestId, int $officerId, int $labId, array $post): int {
        $db = Database::getInstance();
        $s  = fn($v) => htmlspecialchars(strip_tags(trim((string)$v)), ENT_QUOTES, 'UTF-8');

        $measurementData = json_encode(['rows' => $post['meas_rows'] ?? []]);
        $refEquipment    = json_encode($post['ref_equipment'] ?? []);

        $existing = $this->load($requestId);
        $status   = ($post['form_status'] ?? 'draft') === 'submitted' ? 'submitted' : 'draft';

        $params = [
            $s($post['temperature_min'] ?? ''), $s($post['temperature_max'] ?? ''),
            $s($post['humidity_min'] ?? ''),    $s($post['humidity_max'] ?? ''),
            $s($post['pressure_min'] ?? ''),    $s($post['pressure_max'] ?? ''),
            $s($post['place_of_test'] ?? ''),
            $refEquipment,
            $s($post['procedure_used'] ?? ''),  $s($post['norm_standard'] ?? ''),
            $measurementData,
            $s($post['uncertainty_statement'] ?? ''),
            $s($post['coverage_factor'] ?? '2.00'),
            $s($post['confidence_level'] ?? '95%'),
            $s($post['remarks'] ?? ''),
            $status,
        ];

        if ($existing) {
            $db->prepare('UPDATE lab_work_forms SET temperature_min=?,temperature_max=?,humidity_min=?,humidity_max=?,pressure_min=?,pressure_max=?,place_of_test=?,reference_equipment=?,procedure_used=?,norm_standard=?,measurement_data=?,uncertainty_statement=?,coverage_factor=?,confidence_level=?,remarks=?,form_status=? WHERE form_id=?')
               ->execute(array_merge($params, [$existing['form_id']]));
            return $existing['form_id'];
        } else {
            $db->prepare('INSERT INTO lab_work_forms (request_id,officer_id,lab_id,temperature_min,temperature_max,humidity_min,humidity_max,pressure_min,pressure_max,place_of_test,reference_equipment,procedure_used,norm_standard,measurement_data,uncertainty_statement,coverage_factor,confidence_level,remarks,form_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
               ->execute(array_merge([$requestId, $officerId, $labId], $params));
            return (int)$db->lastInsertId();
        }
    }

    public function load(int $requestId): ?array {
        $db   = Database::getInstance();
        $stmt = $db->prepare('SELECT * FROM lab_work_forms WHERE request_id = ?');
        $stmt->execute([$requestId]);
        return $stmt->fetch() ?: null;
    }

    public function isSubmitted(array $formData): bool {
        return ($formData['form_status'] ?? '') === 'submitted';
    }
}
