<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $data = json_decode(file_get_contents('php://input'), true);

        if (!is_array($data)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON body']);
            exit;
        }

        if (!isset($data['household_id']) || !is_numeric($data['household_id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing or invalid household_id']);
            exit;
        }

        if (!isset($data['verifier_name']) || trim((string)$data['verifier_name']) === '') {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required field: verifier_name']);
            exit;
        }

        $error = null;
        $verificationStatus = normalizeVerificationStatus($data['verification_status'] ?? null, $error, false);
        if ($verificationStatus === null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $evidencePhotoCount = normalizeEvidencePhotoCount($data['evidence_photo_count'] ?? null, $error);
        if ($evidencePhotoCount === null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $dataConfidenceScore = normalizeDataConfidenceScore($data['data_confidence_score'] ?? null, $error);
        if ($dataConfidenceScore === null && $error !== null) {
            http_response_code(400);
            echo json_encode(['error' => $error]);
            exit;
        }

        $householdId = (int)$data['household_id'];
        $verifierName = trim((string)$data['verifier_name']);
        $verifierRole = isset($data['verifier_role']) ? trim((string)$data['verifier_role']) : null;
        if ($verifierRole === '') {
            $verifierRole = null;
        }

        $fieldNote = isset($data['field_note']) ? trim((string)$data['field_note']) : null;
        if ($fieldNote === '') {
            $fieldNote = null;
        }

        $verifiedAt = isset($data['verified_at']) && trim((string)$data['verified_at']) !== ''
            ? trim((string)$data['verified_at'])
            : date('Y-m-d H:i:s');

        $verifiedDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $verifiedAt);
        if (!$verifiedDateTime || $verifiedDateTime->format('Y-m-d H:i:s') !== $verifiedAt) {
            http_response_code(400);
            echo json_encode(['error' => 'verified_at must be in YYYY-MM-DD HH:MM:SS format']);
            exit;
        }

        $db = getDB();
        if (!householdExists($db, $householdId)) {
            http_response_code(404);
            echo json_encode(['error' => 'Household not found']);
            exit;
        }

        $insertStmt = $db->prepare('
            INSERT INTO verification_logs (
                household_id,
                verification_status,
                verifier_name,
                verifier_role,
                field_note,
                evidence_photo_count,
                data_confidence_score,
                verified_at
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ');

        $insertStmt->execute([
            $householdId,
            $verificationStatus,
            $verifierName,
            $verifierRole,
            $fieldNote,
            $evidencePhotoCount,
            $dataConfidenceScore,
            $verifiedAt
        ]);

        $updateHouseholdStmt = $db->prepare('UPDATE households SET verification_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?');
        $updateHouseholdStmt->execute([$verificationStatus, $householdId]);

        $id = (int)$db->lastInsertId();
        $resultStmt = $db->prepare('
            SELECT
                vl.*,
                h.household_code,
                h.head_name
            FROM verification_logs vl
            JOIN households h ON h.id = vl.household_id
            WHERE vl.id = ?
        ');
        $resultStmt->execute([$id]);
        $verificationLog = $resultStmt->fetch(PDO::FETCH_ASSOC);

        $household = getHouseholdById($db, $householdId);

        echo json_encode([
            'success' => true,
            'verification_log' => $verificationLog,
            'household' => $household
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>