<?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)) {
            $data = [];
        }

        $db = getDB();

        $households = [];
        if (isset($data['household_id']) && $data['household_id'] !== null && $data['household_id'] !== '') {
            if (!is_numeric($data['household_id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'household_id must be numeric']);
                exit;
            }

            $stmt = $db->prepare('SELECT * FROM households WHERE id = ?');
            $stmt->execute([(int)$data['household_id']]);
            $household = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$household) {
                http_response_code(404);
                echo json_encode(['error' => 'Household not found']);
                exit;
            }

            $households[] = $household;
        } else {
            $stmt = $db->query('SELECT * FROM households ORDER BY id ASC');
            $households = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

        if (empty($households)) {
            echo json_encode([
                'success' => true,
                'message' => 'No households to score',
                'computed_count' => 0,
                'scores' => []
            ]);
            exit;
        }

        $scored = [];
        foreach ($households as $household) {
            $scoreData = computeHouseholdScores($db, $household);
            upsertHouseholdScore($db, $household['id'], $scoreData);

            $scored[] = [
                'household_id' => (int)$household['id'],
                'household_code' => $household['household_code'],
                'head_name' => $household['head_name'],
                'skr' => $scoreData['skr'],
                'sag' => $scoreData['sag'],
                'spi' => $scoreData['spi'],
                'priority_level' => $scoreData['priority_level']
            ];
        }

        usort($scored, function ($a, $b) {
            if ($a['spi'] === $b['spi']) {
                return 0;
            }
            return ($a['spi'] < $b['spi']) ? 1 : -1;
        });

        echo json_encode([
            'success' => true,
            'computed_count' => count($scored),
            'scores' => $scored,
            'score_version' => 'v1'
        ]);
    } 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']);
}
?>