<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require '../config.php';
session_start();

// ------------------------------------------------------------------
// 1. SECURITY & ACCESS CONTROL CHECK
// ------------------------------------------------------------------
$userId = $_SESSION['user_id'] ?? null;
$userRole = strtolower(trim((string)($_SESSION['role'] ?? '')));

if (!$userId || !in_array($userRole, ['manager', 'admin', 'superadmin', 'supervisor'])) {
    die("CRITICAL SECURITY ERROR: Unauthorized access attempt to backend data parameters.");
}

// ------------------------------------------------------------------
// 2. REQUEST METHOD VALIDATION
// ------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: my_profile.php"); // Fallback safety redirect
    exit;
}

// ------------------------------------------------------------------
// 3. CAPTURE & SANITIZE DATA PARAMS
// ------------------------------------------------------------------
$reportDate       = $_POST['report_date'] ?? date('Y-m-d');
$managerName      = trim((string)($_POST['manager_name'] ?? ''));
$shiftTimeline    = trim((string)($_POST['shift_timeline'] ?? ''));
$foRollCall       = trim((string)($_POST['fo_rollcall'] ?? ''));
$vacantRoomsList  = trim((string)($_POST['vacant_rooms'] ?? ''));
$gen1Time         = trim((string)($_POST['gen1_time'] ?? ''));
$gen2Time         = trim((string)($_POST['gen2_time'] ?? ''));
$g1Fuel           = trim((string)($_POST['g1_fuel'] ?? ''));
$g2Fuel           = trim((string)($_POST['g2_fuel'] ?? ''));
$surfaceFuel      = trim((string)($_POST['surface_fuel'] ?? ''));
$undergroundFuel  = trim((string)($_POST['underground_fuel'] ?? ''));

// ------------------------------------------------------------------
// 4. PARSE DYNAMIC INSPECTION ENTRIES (BUILDING METRICS LOG)
// ------------------------------------------------------------------
// This builds an associative array of all status choices & text entries 
$inspectionPayload = [
    'front_office' => [
        'expected_arrival_status' => $_POST['fo_arr'] ?? 'N/A',
        'expected_arrival_note'   => trim((string)($_POST['fo_arr_comment'] ?? '')),
        'long_stay_status'        => $_POST['fo_long'] ?? 'N/A',
        'long_stay_note'          => trim((string)($_POST['fo_long_comment'] ?? ''))
    ],
    'infrastructure' => [
        'generator_1_fuel' => $g1Fuel,
        'generator_2_fuel' => $g2Fuel,
        'surface_tank'     => $surfaceFuel,
        'underground_tank' => $undergroundFuel
    ]
];

// Convert structured checklist payload to JSON safely for single-field logging
$maintenanceDefectsLog = json_encode($inspectionPayload, JSON_UNESCAPED_UNICODE);

// ------------------------------------------------------------------
// 5. SECURE PREPARED STATEMENTS SQL INTERFACE
// ------------------------------------------------------------------
$sql = "INSERT INTO mod_reports (
            report_date, 
            manager_name, 
            shift_timeline, 
            fo_roll_call, 
            vacant_rooms_list, 
            gen1_runtime, 
            gen2_runtime, 
            gen1_fuel_level, 
            gen2_fuel_level, 
            surface_tank_level, 
            underground_tank_level, 
            maintenance_defects_log
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param(
        "ssssssssssss",
        $reportDate,
        $managerName,
        $shiftTimeline,
        $foRollCall,
        $vacantRoomsList,
        $gen1Time,
        $gen2Time,
        $g1Fuel,
        $g2Fuel,
        $surfaceFuel,
        $undergroundFuel,
        $maintenanceDefectsLog
    );

    if ($stmt->execute()) {
        // SUCCESS: Show parameters matching your dashboard success architecture
        $_SESSION['success_flash'] = "MOD Logbook successfully committed to database registry.";
        header("Location: dashboard.php?status=success");
        exit;
    } else {
        error_log("Database Execution Error: " . $stmt->error);
        die("CRITICAL ENGINE ERROR: Could not dispatch parameters to operational database ledger.");
    }
    $stmt->close();
} else {
    error_log("Database Preparation Error: " . $conn->error);
    die("CRITICAL CONFIGURATION ERROR: Prepared statement pipeline initialization failure.");
}
?>