<?php
include('config.php');

header('Content-Type: application/json');

// Read input data
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'No data received.']);
    exit;
}

$errors = [];
foreach ($data as $row) {
    $barangay_name = $row['Barangay'] ?? null; // Adjust column names to match your Excel headers
    $total_households = $row['Total Households'] ?? null;

    if (!$barangay_name || !$total_households) {
        $errors[] = "Invalid row: " . json_encode($row);
        continue;
    }

    // Check if barangay already exists
    $check_query = "SELECT * FROM barangay_tb WHERE barangay_name = '$barangay_name'";
    $check_result = mysqli_query($db, $check_query);

    if (mysqli_num_rows($check_result) > 0) {
        // Barangay exists, update the record
        $update_query = "UPDATE barangay_tb SET total_households = '$total_households' WHERE barangay_name = '$barangay_name'";

        if (!mysqli_query($db, $update_query)) {
            $errors[] = "Database error while updating row: " . json_encode($row);
        }
    } else {
        // Barangay doesn't exist, insert a new record
        $insert_query = "INSERT INTO barangay_tb (barangay_name, total_households) VALUES ('$barangay_name', '$total_households')";

        if (!mysqli_query($db, $insert_query)) {
            $errors[] = "Database error while inserting row: " . json_encode($row);
        }
    }
}

if (empty($errors)) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => implode("\n", $errors)]);
}
?>
