<?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_name = mysqli_real_escape_string($conn, $_POST['equipment_name']);
$equipment_code = mysqli_real_escape_string($conn, $_POST['equipment_code']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$status = mysqli_real_escape_string($conn, $_POST['status']);
$description = mysqli_real_escape_string($conn, $_POST['description'] ?? '');
$manufacturer = mysqli_real_escape_string($conn, $_POST['manufacturer'] ?? '');
$model_number = mysqli_real_escape_string($conn, $_POST['model_number'] ?? '');
$serial_number = mysqli_real_escape_string($conn, $_POST['serial_number'] ?? '');
$location = mysqli_real_escape_string($conn, $_POST['location'] ?? '');
$purchase_date = !empty($_POST['purchase_date']) ? $_POST['purchase_date'] : NULL;
$warranty_expiry = !empty($_POST['warranty_expiry']) ? $_POST['warranty_expiry'] : NULL;
$user_id = $_SESSION['user_id'];

if(empty($equipment_name) || empty($equipment_code) || empty($department)) {
    echo json_encode(['success' => false, 'message' => 'Please fill in all required fields']);
    exit();
}

mysqli_begin_transaction($conn);

try {
    // Check if equipment code already exists
    $check_sql = "SELECT equipment_id FROM lab_equipment WHERE equipment_code = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('s', $equipment_code);
    $stmt->execute();
    
    if($stmt->get_result()->num_rows > 0) {
        throw new Exception("Equipment code already exists");
    }
    
    // Insert equipment
    $insert_sql = "INSERT INTO lab_equipment (
                    equipment_name, equipment_code, department, status,
                    description, manufacturer, model_number, serial_number,
                    location, purchase_date, warranty_expiry, created_at
                   ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param('sssssssssss', 
        $equipment_name, $equipment_code, $department, $status,
        $description, $manufacturer, $model_number, $serial_number,
        $location, $purchase_date, $warranty_expiry
    );
    
    if(!$stmt->execute()) {
        throw new Exception("Failed to add equipment");
    }
    
    $equipment_id = $conn->insert_id;
    
    // Log activity
    $log_sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                VALUES (?, 'CREATE', 'EQUIPMENT', ?, ?, ?, NOW())";
    $stmt = $conn->prepare($log_sql);
    $description_log = "Added new equipment: " . $equipment_name . " (" . $equipment_code . ")";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param('iiss', $user_id, $equipment_id, $description_log, $ip_address);
    $stmt->execute();
    
    mysqli_commit($conn);
    
    echo json_encode([
        'success' => true,
        'message' => 'Equipment added successfully',
        'equipment_id' => $equipment_id
    ]);
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

mysqli_close($conn);
?>