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

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

// Check database connection
if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Get the raw POST data
$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE || !isset($data['data'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid data format']);
    exit;
}

try {
    // Begin transaction
    $db->begin_transaction();
    
    // Clear existing data
    $db->query("TRUNCATE TABLE pump_forecast_data");
    
    // Prepare statement
    $stmt = $db->prepare("INSERT INTO pump_forecast_data (pump, barangays, total_supply, monthly_demand) VALUES (?, ?, ?, ?)");
    
    foreach ($data['data'] as $row) {
        // Validate data
        if (!isset($row['pump']) || !isset($row['barangays']) || 
            !isset($row['total_supply']) || !isset($row['monthly_demand'])) {
            continue; // Skip invalid rows
        }
        
        $stmt->bind_param("isdd", 
            $row['pump'], 
            $row['barangays'], 
            $row['total_supply'], 
            $row['monthly_demand']
        );
        $stmt->execute();
    }
    
    // Commit transaction
    $db->commit();
    
    echo json_encode(['status' => 'success']);
} catch (Exception $e) {
    $db->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>