<?php
session_start();
require_once '../../../config/database.php';

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

$database = new Database();
$conn = $database->getConnection();

$room_id = isset($_POST['room_id']) ? intval($_POST['room_id']) : 0;
$device_name = isset($_POST['device_name']) ? trim($_POST['device_name']) : '';
$device_type = isset($_POST['device_type']) ? trim($_POST['device_type']) : '';
$device_model = isset($_POST['device_model']) ? trim($_POST['device_model']) : '';
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
$unit_price = isset($_POST['unit_price']) ? floatval($_POST['unit_price']) : 0;
$installation_cost = isset($_POST['installation_cost']) ? floatval($_POST['installation_cost']) : 0;
$total_price = isset($_POST['total_price']) ? floatval($_POST['total_price']) : 0;
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

if ($room_id <= 0 || empty($device_name) || $unit_price <= 0) {
    echo json_encode(['success' => false, 'message' => 'بيانات غير مكتملة']);
    exit;
}

try {
    $query = "INSERT INTO iot_project_devices 
              (room_id, device_name, device_type, device_model, quantity, unit_price, installation_cost, total_price, notes) 
              VALUES (:room_id, :device_name, :device_type, :device_model, :quantity, :unit_price, :installation_cost, :total_price, :notes)";
    
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':room_id', $room_id);
    $stmt->bindParam(':device_name', $device_name);
    $stmt->bindParam(':device_type', $device_type);
    $stmt->bindParam(':device_model', $device_model);
    $stmt->bindParam(':quantity', $quantity);
    $stmt->bindParam(':unit_price', $unit_price);
    $stmt->bindParam(':installation_cost', $installation_cost);
    $stmt->bindParam(':total_price', $total_price);
    $stmt->bindParam(':notes', $notes);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true, 
            'message' => 'تم إضافة الجهاز بنجاح',
            'device_id' => $conn->lastInsertId()
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'فشل إضافة الجهاز']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ: ' . $e->getMessage()]);
}
?>
