<?php
session_start();
ini_set('display_errors', 0); // Secure production JSON output
error_reporting(E_ALL);
header('Content-Type: application/json');

// Relative connection path to include db configuration
require_once __DIR__ . '/../../includes/db.php';

$response = ['success' => false, 'message' => 'Invalid Request Method or Action'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // ==============================================================================
    // ACTION: ADD NEW LAB BENCH / SUB-DEPARTMENT
    // ==============================================================================
    if ($action === 'add') {
        $sub_dept_name = trim($_POST['sub_dept_name'] ?? '');
        
        if (empty($sub_dept_name)) {
            $response['message'] = 'Lab sub-department name cannot be empty.';
            echo json_encode($response);
            exit;
        }

        // Duplicate entry verification
        $stmt = $conn->prepare("SELECT id FROM lab_sub_departments WHERE sub_dept_name = ?");
        $stmt->bind_param("s", $sub_dept_name);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $response['message'] = 'A lab sub-department with this exact name already exists.';
            echo json_encode($response);
            exit;
        }
        $stmt->close();

        // Secure insertion
        $stmt = $conn->prepare("INSERT INTO lab_sub_departments (sub_dept_name, is_active) VALUES (?, 1)");
        $stmt->bind_param("s", $sub_dept_name);
        if ($stmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'Lab sub-department added successfully!';
        } else {
            $response['message'] = 'Database error: Failed to save lab sub-department.';
        }
        $stmt->close();
    } 
    
    // ==============================================================================
    // ACTION: UPDATE EXISTING LAB BENCH
    // ==============================================================================
    elseif ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $sub_dept_name = trim($_POST['sub_dept_name'] ?? '');
        $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;

        if ($id <= 0 || empty($sub_dept_name)) {
            $response['message'] = 'Required fields are missing or invalid.';
            echo json_encode($response);
            exit;
        }

        // Check if name conflicts with another record
        $stmt = $conn->prepare("SELECT id FROM lab_sub_departments WHERE sub_dept_name = ? AND id != ?");
        $stmt->bind_param("si", $sub_dept_name, $id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $response['message'] = 'Another lab sub-department is already using this name.';
            echo json_encode($response);
            exit;
        }
        $stmt->close();

        // Execute update
        $stmt = $conn->prepare("UPDATE lab_sub_departments SET sub_dept_name = ?, is_active = ? WHERE id = ?");
        $stmt->bind_param("sii", $sub_dept_name, $is_active, $id);
        if ($stmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'Lab sub-department records updated successfully!';
        } else {
            $response['message'] = 'Database error: Failed to update records.';
        }
        $stmt->close();
    }
    
    // ==============================================================================
    // ACTION: INLINE AJAX TOGGLE STATUS
    // ==============================================================================
    elseif ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            $response['message'] = 'Invalid lab sub-department ID targeting requested.';
            echo json_encode($response);
            exit;
        }

        // Fetch current active status
        $stmt = $conn->prepare("SELECT is_active FROM lab_sub_departments WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($result) {
            $new_status = ($result['is_active'] == 1) ? 0 : 1;
            
            $stmt = $conn->prepare("UPDATE lab_sub_departments SET is_active = ? WHERE id = ?");
            $stmt->bind_param("ii", $new_status, $id);
            if ($stmt->execute()) {
                $response['success'] = true;
                $response['message'] = 'Workstation routing accessibility changed successfully.';
                $response['new_status'] = $new_status;
            } else {
                $response['message'] = 'Failed to shift bench runtime status.';
            }
            $stmt->close();
        } else {
            $response['message'] = 'Target lab sub-department records not found.';
        }
    }
}

echo json_encode($response);
exit;