<?php
// Backfill missing household fields for existing need_points
header('Content-Type: application/json');
require_once 'config.php';

try {
    $db = getDB();

    // Fetch points missing any of the new fields
    $stmt = $db->query("SELECT id, name FROM need_points WHERE household_name IS NULL OR TRIM(household_name) = '' OR head_name IS NULL OR TRIM(head_name) = '' OR economic_status IS NULL OR TRIM(economic_status) = ''");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($rows)) {
        echo json_encode(['success' => true, 'updated' => 0, 'message' => 'No need_points required backfill.']);
        exit;
    }

    $updateStmt = $db->prepare('UPDATE need_points SET household_name = ?, head_name = ?, economic_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?');

    $firstNames = ['Ahmad','Budi','Siti','Aulia','Rizal','Dewi','Agus','Fitri','Hendra','Yulia'];
    $lastNames = ['Santoso','Wijaya','Pratama','Hidayat','Saputra','Nur','Ibrahim','Setiawan','Rahman','Putri'];
    $statuses = ['sangat_miskin','miskin','rentan','cukup','baik'];

    $db->beginTransaction();
    $updated = 0;
    $examples = [];
    foreach ($rows as $r) {
        $id = (int)$r['id'];
        $hhName = 'Keluarga ' . substr(md5($r['name'] . $id . microtime(true)), 0, 8);
        $headName = $firstNames[array_rand($firstNames)] . ' ' . $lastNames[array_rand($lastNames)];
        $econ = $statuses[array_rand($statuses)];

        $updateStmt->execute([$hhName, $headName, $econ, $id]);
        $updated++;
        if (count($examples) < 8) {
            $examples[] = ['id' => $id, 'household_name' => $hhName, 'head_name' => $headName, 'economic_status' => $econ];
        }
    }
    $db->commit();

    echo json_encode(['success' => true, 'updated' => $updated, 'examples' => $examples]);
} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) $db->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

// If called from CLI, also print a newline
if (php_sapi_name() === 'cli') echo "\n";

?>
