<?php
session_start();
include '../layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$equipment_id = intval($_POST['equipment_id']);
$new_status = mysqli_real_escape_string($conn, $_POST['status']);
$user_id = $_SESSION['user_id'];

// Validate status
$valid_statuses = ['OPERATIONAL', 'UNDER_MAINTENANCE', 'OUT_OF_SERVICE'];
if(!in_array($new_status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // Get equipment details
    $eq_query = "SELECT equipment_name, equipment_code, status as current_status FROM lab_equipment WHERE equipment_id = ?";
    $stmt = $conn->prepare($eq_query);
    $stmt->bind_param('i', $equipment_id);
    $stmt->execute();
    $equipment = $stmt->get_result()->fetch_assoc();
    
    if(!$equipment) {
        throw new Exception("Equipment not found");
    }
    
    // Update equipment status
    $update_sql = "UPDATE lab_equipment SET status = ?, updated_at = NOW()";
    
    // Add maintenance date if marking as maintenance
    if($new_status === 'UNDER_MAINTENANCE') {
        $update_sql .= ", last_maintenance_date = NOW()";
    }
    
    $update_sql .= " WHERE equipment_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('si', $new_status, $equipment_id);
    
    if(!$stmt->execute()) {
        throw new Exception("Failed to update equipment status");
    }
    
    // Log activity
    $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                VALUES (?, 'UPDATE', 'EQUIPMENT', ?, ?, ?, NOW())";
    $stmt = $conn->prepare($log_sql);
    $description = "Updated equipment status from " . $equipment['current_status'] . " to " . $new_status . 
                   " for " . $equipment['equipment_name'] . " (" . $equipment['equipment_code'] . ")";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param('iiss', $user_id, $equipment_id, $description, $ip_address);
    $stmt->execute();
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Equipment status updated successfully',
        'new_status' => $new_status
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

mysqli_close($conn);
?>