<?php
/**
 * controllers/blockSubmit.php
 *
 * Handles Create and Edit (update) submissions for block_info records.
 * Redirects back to /dashboard/crop-cards/ on success or failure.
 */

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

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

requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /dashboard/crop-cards/');
    exit;
}

if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    $_SESSION['flash_error'] = 'Invalid security token. Please try again.';
    header('Location: /dashboard/crop-cards/');
    exit;
}

$action    = $_POST['action'] ?? '';
$userId    = getCurrentUserId();
$pdo       = getDBConnection();

// Shared field sanitisation
$name      = trim($_POST['name']      ?? '');
$blockId   = trim($_POST['block_id']  ?? '');
$location  = trim($_POST['location']  ?? '');
$areaHa    = is_numeric($_POST['area_ha'] ?? '') ? (float) $_POST['area_ha'] : 0;
$gps       = trim($_POST['gps']       ?? '');
$soilType  = trim($_POST['analysis_type'] ?? '');

if ($name === '' || $blockId === '') {
    $_SESSION['flash_error'] = 'Block ID and Block Name are required.';
    header('Location: /dashboard/crop-cards/');
    exit;
}

if ($action === 'create') {
    $stmt = $pdo->prepare('
        INSERT INTO block_info (modx_user_id, name, block_id, location, area, gps, status, date_added)
        VALUES (?, ?, ?, ?, ?, ?, 0, CURDATE())
    ');
    $stmt->execute([$userId, $name, $blockId, $location, (int) $areaHa, $gps]);

    $_SESSION['flash_success'] = 'Paddock "' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '" created.';
    header('Location: /dashboard/crop-cards/');
    exit;
}

if ($action === 'edit') {
    $recordId = (int) ($_POST['record_id'] ?? 0);

    if ($recordId <= 0) {
        $_SESSION['flash_error'] = 'Invalid record.';
        header('Location: /dashboard/crop-cards/');
        exit;
    }

    // Ownership check
    $check = $pdo->prepare('SELECT id FROM block_info WHERE id = ? AND modx_user_id = ? LIMIT 1');
    $check->execute([$recordId, $userId]);
    if (!$check->fetch()) {
        $_SESSION['flash_error'] = 'Record not found or access denied.';
        header('Location: /dashboard/crop-cards/');
        exit;
    }

    $stmt = $pdo->prepare('
        UPDATE block_info
        SET name = ?, block_id = ?, location = ?, area = ?, gps = ?
        WHERE id = ? AND modx_user_id = ?
    ');
    $stmt->execute([$name, $blockId, $location, (int) $areaHa, $gps, $recordId, $userId]);

    $_SESSION['flash_success'] = 'Paddock "' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '" updated.';
    header('Location: /dashboard/crop-cards/');
    exit;
}

// Unknown action
header('Location: /dashboard/crop-cards/');
exit;
