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

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

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

switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['device_id']) || !isset($data['email']) || !isset($data['pop'])) {
            http_response_code(400);
            echo json_encode(['error' => 'device_id, email, and pop are required']);
            break;
        }
        
        $device_id = $data['device_id'];
        $email = $data['email'];
        $pop_code = $data['pop'];
        
        // Get user by email
        $stmt = $con->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(404);
            echo json_encode(['error' => 'User not found']);
            break;
        }
        
        $user_id = $result->fetch_assoc()['id'];
        
        // Check if device already exists
        $stmt = $con->prepare("SELECT id, owner_id FROM devices WHERE device_id = ?");
        $stmt->bind_param("s", $device_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $device = $result->fetch_assoc();
            
            // Check if device belongs to this user
            if ((int)$device['owner_id'] !== (int)$user_id) {
                http_response_code(403);
                echo json_encode(['error' => 'Device already claimed by another user']);
                break;
            }
            
            // Device already claimed by this user
            echo json_encode([
                'success' => true,
                'message' => 'Device already claimed',
                'device_id' => $device['id']
            ]);
            break;
        }
        
        // Register new device (new schema)
        $device_name = "ESP32 Device - " . substr($device_id, -8);
        $esp_model = $data['esp_model'] ?? 'ESP32';
        if (!in_array($esp_model, ['ESP32', 'ESP32-S2', 'ESP32-S3'], true)) {
            $esp_model = 'ESP32';
        }
        
        $metadata = json_encode([
            'pop_code' => $pop_code,
            'claimed_by_email' => $email,
            'claimed_at' => date('Y-m-d H:i:s')
        ]);
        
        $stmt = $con->prepare("
            INSERT INTO devices (device_id, name, owner_id, esp_model, status, current_mode, metadata)
            VALUES (?, ?, ?, ?, 'offline', 'SETUP', ?)
        ");
        $stmt->bind_param("ssiss", $device_id, $device_name, $user_id, $esp_model, $metadata);
        
        if ($stmt->execute()) {
            $device_db_id = $stmt->insert_id;
            
            // Add owner permission
            $stmt = $con->prepare("
                INSERT INTO device_permissions (device_id, user_id, permission_type)
                VALUES (?, ?, 'owner')
            ");
            $stmt->bind_param("ii", $device_db_id, $user_id);
            $stmt->execute();
            
            echo json_encode([
                'success' => true,
                'message' => 'Device claimed successfully',
                'device_id' => $device_db_id
            ]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to claim device']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}
?>
