<?php
/**
 * base-saturation-pie.php
 *
 * AJAX endpoint — returns base saturation percentages as JSON for pie chart.
 * Requires authentication.
 */

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../lib/auth.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorised']);
    exit;
}

$record_id = (int)  ($_GET['rid']  ?? 0);
$rand_id   = (float)($_GET['rand'] ?? 0);

if (!$record_id || !$rand_id) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid parameters']);
    exit;
}

try {
    $pdo  = getDBConnection();
    $stmt = $pdo->prepare(
        'SELECT BS_ca2, BS_mg2, BS_k, BS_na, BS_ob, BS_h
           FROM `soil_records`
          WHERE id = ? AND rand = ?
          LIMIT 1'
    );
    $stmt->execute([$record_id, $rand_id]);
    $row = $stmt->fetch();

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

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

    echo json_encode([$row]);
} catch (PDOException $e) {
    error_log('base-saturation-pie.php DB error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
