<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';

// Kullanıcı kimlik doğrulama
function authenticate() {
    session_start();
    
    if (!isset($_SESSION['user_id'])) {
        return null;
    }
    
    return $_SESSION['user_id'];
}

switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
        $user_id = authenticate();
        
        if (!$user_id) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id']) || !isset($data['mode'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id and mode are required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $mode = $data['mode'];
        
        // Geçerli modları kontrol et
        $valid_modes = ['SETUP', 'PROVISION', 'ONLINE', 'MOTOR_CONTROL', 'PROTECTION'];
        if (!in_array($mode, $valid_modes)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid mode']);
            break;
        }
        
        // Cihaz yetkisi kontrolü
        $stmt = $con->prepare("
            SELECT d.id FROM devices d 
            LEFT JOIN device_permissions dp ON d.id = dp.device_id 
            WHERE d.device_id = ? AND dp.user_id = ? AND dp.permission_type IN ('owner', 'controller')
        ");
        $stmt->bind_param("si", $device_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'No permission to control this device']);
            break;
        }
        
        $device_db_id = $result->fetch_assoc()['id'];
        
        // Mod değişikliğini veritabanına kaydet
        $stmt = $con->prepare("
            INSERT INTO device_mode_changes (device_id, user_id, old_mode, new_mode, changed_at)
            VALUES (?, ?, (SELECT current_mode FROM devices WHERE id = ?), ?, NOW())
        ");
        $stmt->bind_param("iiss", $device_db_id, $user_id, $device_db_id, $mode);
        $stmt->execute();
        
        // Cihazın mevcut modunu güncelle
        $stmt = $con->prepare("
            UPDATE devices SET current_mode = ?, last_mode_change = NOW() WHERE id = ?
        ");
        $stmt->bind_param("si", $mode, $device_db_id);
        $stmt->execute();
        
        // Mod değişikliği log'u
        $stmt = $con->prepare("
            INSERT INTO device_logs (device_id, user_id, action, details, created_at)
            VALUES (?, ?, 'mode_change', ?, NOW())
        ");
        $details = json_encode(['old_mode' => 'previous', 'new_mode' => $mode]);
        $stmt->bind_param("iiss", $device_db_id, $user_id, $details);
        $stmt->execute();
        
        // Cihaza WebSocket ile bildirim gönder
        sendWebSocketNotification($device_id, [
            'type' => 'mode_change',
            'mode' => $mode,
            'user_id' => $user_id,
            'timestamp' => time()
        ]);
        
        // Mobil uygulama için push notification gönder
        sendPushNotification($user_id, [
            'title' => 'Mod Değiştirildi',
            'body' => "Cihaz modu {$mode} olarak değiştirildi",
            'device_id' => $device_id,
            'type' => 'mode_change'
        ]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Mode changed successfully',
            'mode' => $mode,
            'timestamp' => time()
        ]);
        break;
        
    case 'GET':
        $user_id = authenticate();
        
        if (!$user_id) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            break;
        }
        
        $device_id = $_GET['device_id'] ?? null;
        
        if (!$device_id) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id is required']);
            break;
        }
        
        // Cihaz yetkisi kontrolü
        $stmt = $con->prepare("
            SELECT d.id, d.current_mode, d.last_mode_change, d.name as device_name
            FROM devices d 
            LEFT JOIN device_permissions dp ON d.id = dp.device_id 
            WHERE d.device_id = ? AND dp.user_id = ? AND dp.permission_type IN ('owner', 'controller', 'viewer')
        ");
        $stmt->bind_param("si", $device_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(403);
            echo json_encode(['error' => 'No permission to view this device']);
            break;
        }
        
        $device = $result->fetch_assoc();
        
        // Mod geçmişini al
        $stmt = $con->prepare("
            SELECT old_mode, new_mode, changed_at, u.username
            FROM device_mode_changes mc
            JOIN users u ON mc.user_id = u.id
            WHERE mc.device_id = ?
            ORDER BY mc.changed_at DESC
            LIMIT 10
        ");
        $stmt->bind_param("i", $device['id']);
        $stmt->execute();
        $history = [];
        
        while ($row = $stmt->fetch_assoc()) {
            $history[] = $row;
        }
        
        echo json_encode([
            'success' => true,
            'device' => [
                'device_id' => $device_id,
                'device_name' => $device['device_name'],
                'current_mode' => $device['current_mode'],
                'last_mode_change' => $device['last_mode_change']
            ],
            'history' => $history
        ]);
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}

// WebSocket bildirim gönderme
function sendWebSocketNotification($device_id, $data) {
    // WebSocket sunucusuna bildirim gönder
    $ch = curl_init();
    $url = 'ws://localhost:8080/notify';
    
    $payload = json_encode([
        'device_id' => $device_id,
        'data' => $data
    ]);
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    curl_exec($ch);
    curl_close($ch);
}

// Push notification gönderme
function sendPushNotification($user_id, $data) {
    // Kullanıcının FCM token'ını al
    $stmt = $con->prepare("SELECT fcm_token FROM user_fcm_tokens WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($row = $result->fetch_assoc()) {
        $fcm_token = $row['fcm_token'];
        
        // FCM bildirim gönder
        $notification = [
            'to' => $fcm_token,
            'notification' => [
                'title' => $data['title'],
                'body' => $data['body'],
                'sound' => 'default'
            ],
            'data' => $data
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: key=YOUR_FCM_SERVER_KEY',
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        curl_exec($ch);
        curl_close($ch);
    }
}
?>
