<?php

/**
 * Debug Device Validation Script
 *
 * Jalankan di server untuk debug mengapa device validation tidak berfungsi
 * URL: /debug-device-validation.php?email1=user1@email.com&email2=user2@email.com
 */

require_once __DIR__ . '/../vendor/autoload.php';
$app = require_once __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$kernel->handle(Illuminate\Http\Request::capture());

use App\Models\User;
use App\Models\UserDevice;
use App\Models\Company;

header('Content-Type: text/plain; charset=utf-8');
echo "=== DEBUG DEVICE VALIDATION ===\n\n";

$email1 = $_GET['email1'] ?? 'riel.msf28@gmail.com';
$email2 = $_GET['email2'] ?? 'arioraga@gmail.com';

// Get users
$user1 = User::where('email', $email1)->first();
$user2 = User::where('email', $email2)->first();

if (!$user1) {
    echo "ERROR: User dengan email $email1 tidak ditemukan!\n";
    exit;
}

if (!$user2) {
    echo "ERROR: User dengan email $email2 tidak ditemukan!\n";
    exit;
}

echo "User 1: {$user1->name} ({$user1->email}) - Company ID: {$user1->company_id}\n";
echo "User 2: {$user2->name} ({$user2->email}) - Company ID: {$user2->company_id}\n\n";

// Check company settings
$company1 = Company::find($user1->company_id);
$company2 = Company::find($user2->company_id);

echo "=== COMPANY SETTINGS ===\n";
if ($company1) {
    echo "Company 1 ({$company1->name}):\n";
    echo "  - device_validation_enabled: " . ($company1->device_validation_enabled ? 'TRUE' : 'FALSE') . "\n";
    echo "  - max_devices_per_user: " . ($company1->max_devices_per_user ?? 'NULL') . "\n";
    echo "\n";
}

if ($company2 && $company2->id !== $company1?->id) {
    echo "Company 2 ({$company2->name}):\n";
    echo "  - device_validation_enabled: " . ($company2->device_validation_enabled ? 'TRUE' : 'FALSE') . "\n";
    echo "  - max_devices_per_user: " . ($company2->max_devices_per_user ?? 'NULL') . "\n";
    echo "\n";
}

// Check registered devices
echo "=== USER DEVICES ===\n\n";

echo "User 1 ({$user1->email}) devices:\n";
$devices1 = UserDevice::where('user_id', $user1->id)->get();
if ($devices1->isEmpty()) {
    echo "  (Tidak ada device terdaftar)\n";
} else {
    foreach ($devices1 as $device) {
        echo "  - Device ID: {$device->device_id}\n";
        echo "    Status: {$device->status}\n";
        echo "    Model: {$device->device_brand} {$device->device_model}\n";
        echo "    Is Primary: " . ($device->is_primary ? 'Yes' : 'No') . "\n";
        echo "    Last Used: {$device->last_used_at}\n";
        echo "\n";
    }
}

echo "\nUser 2 ({$user2->email}) devices:\n";
$devices2 = UserDevice::where('user_id', $user2->id)->get();
if ($devices2->isEmpty()) {
    echo "  (Tidak ada device terdaftar)\n";
} else {
    foreach ($devices2 as $device) {
        echo "  - Device ID: {$device->device_id}\n";
        echo "    Status: {$device->status}\n";
        echo "    Model: {$device->device_brand} {$device->device_model}\n";
        echo "    Is Primary: " . ($device->is_primary ? 'Yes' : 'No') . "\n";
        echo "    Last Used: {$device->last_used_at}\n";
        echo "\n";
    }
}

// Check if there are shared devices
echo "=== SHARED DEVICE CHECK ===\n\n";

$user1DeviceIds = $devices1->pluck('device_id')->toArray();
$user2DeviceIds = $devices2->pluck('device_id')->toArray();

$sharedDevices = array_intersect($user1DeviceIds, $user2DeviceIds);

if (empty($sharedDevices)) {
    echo "Tidak ada device yang terdaftar oleh kedua user.\n";
} else {
    echo "DITEMUKAN DEVICE YANG SAMA!\n";
    foreach ($sharedDevices as $deviceId) {
        echo "  - Device ID: $deviceId\n";

        // Get registration info for both users
        $dev1 = UserDevice::where('device_id', $deviceId)->where('user_id', $user1->id)->first();
        $dev2 = UserDevice::where('device_id', $deviceId)->where('user_id', $user2->id)->first();

        if ($dev1) {
            echo "    Registered by {$user1->email}: Status={$dev1->status}, Created={$dev1->created_at}\n";
        }
        if ($dev2) {
            echo "    Registered by {$user2->email}: Status={$dev2->status}, Created={$dev2->created_at}\n";
        }
    }
}

echo "\n=== VALIDATION SIMULATION ===\n\n";

// Simulate what would happen if user2 tries to login with user1's device
foreach ($devices1 as $device) {
    $deviceId = $device->device_id;
    $deviceStatus = $device->status;

    echo "Jika user2 ({$user2->email}) login dengan device_id: $deviceId\n";

    // Check if this device would block user2
    $deviceUsedByOther = UserDevice::where('device_id', $deviceId)
        ->where('user_id', '!=', $user2->id)
        ->whereIn('status', [UserDevice::STATUS_APPROVED, UserDevice::STATUS_PENDING])
        ->with('user')
        ->first();

    if ($deviceUsedByOther) {
        echo "  -> HARUS DIBLOK! Device terdaftar ke: {$deviceUsedByOther->user?->email} (Status: {$deviceUsedByOther->status})\n";
    } else {
        echo "  -> TIDAK DIBLOK. Query tidak menemukan device milik user lain.\n";
    }
    echo "\n";
}

echo "=== REKOMENDASI ===\n\n";

if (!$company1?->device_validation_enabled) {
    echo "1. AKTIFKAN device_validation_enabled di company!\n";
    echo "   SQL: UPDATE companies SET device_validation_enabled = 1 WHERE id = {$company1?->id};\n\n";
}

if ($devices1->isEmpty()) {
    echo "2. User 1 tidak punya device terdaftar. Minta user login dari mobile untuk mendaftarkan device.\n\n";
}

echo "3. Pastikan mobile app mengirim device_id saat login:\n";
echo "   - Cek log request login di backend\n";
echo "   - Pastikan DeviceInfoHelper.getDeviceInfo() mengembalikan device_id yang valid\n\n";

echo "4. Setelah user 1 login dan device terdaftar, coba login dengan user 2 dari device yang sama.\n";
echo "   Jika device_validation_enabled=true, login harus GAGAL dengan pesan:\n";
echo "   'Device ini sudah terdaftar oleh user lain'\n\n";

echo "=== END DEBUG ===\n";
