<?php

/**
 * Script untuk mengecek dan sinkronisasi permissions
 * Membandingkan routes di web.php dengan data permissions di database
 * Insert permission baru jika belum ada
 * 
 * CATATAN: Script ini HANYA INSERT, tidak akan UPDATE atau DELETE apapun
 * 
 * Cara pakai: 
 * - Interactive mode: php cek_permission.php
 * - Auto insert mode: php cek_permission.php --auto
 * - Dry run (hanya lihat): php cek_permission.php --dry-run
 */

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;

// Parse command line arguments
$autoMode = in_array('--auto', $argv);
$dryRun = in_array('--dry-run', $argv);

if ($dryRun) {
    echo "🔍 DRY RUN MODE - Tidak ada perubahan yang akan dilakukan\n\n";
}

echo "==============================================\n";
echo "  PERMISSION CHECKER & SYNC\n";
echo "==============================================\n\n";

try {
    // Test koneksi database
    DB::connection()->getPdo();
    echo "✓ Database connection: OK\n\n";
} catch (\Exception $e) {
    echo "✗ Database connection: FAILED\n";
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}

// Ambil semua routes dari aplikasi
echo "Mengambil daftar routes...\n";
$routes = Route::getRoutes();
$routeNames = [];

foreach ($routes as $route) {
    $name = $route->getName();
    
    // Skip routes tanpa nama
    if (empty($name)) {
        continue;
    }
    
    // Skip routes yang di-generate otomatis oleh Laravel
    if (strpos($name, 'generated::') === 0) {
        continue;
    }
    
    // Skip routes yang tidak perlu permission (login, logout, register, dll)
    $skipRoutes = [
        'login',
        'login.perform',
        'logout.perform',
        'register.show',
        'register.perform',
        'home.index',
        'change.store',
        'ajax.checkPermissions',
        'sanctum.csrf-cookie'
    ];
    
    if (in_array($name, $skipRoutes)) {
        continue;
    }
    
    $routeNames[] = $name;
}

$routeNames = array_unique($routeNames);
sort($routeNames);

echo "✓ Total routes dengan nama: " . count($routeNames) . "\n\n";

// Ambil permissions yang sudah ada di database
echo "Mengambil daftar permissions dari database...\n";
$existingPermissions = DB::table('permissions')
    ->pluck('name')
    ->toArray();

echo "✓ Total permissions di database: " . count($existingPermissions) . "\n\n";

// Cari permissions yang belum ada
$missingPermissions = array_diff($routeNames, $existingPermissions);
$existingInBoth = array_intersect($routeNames, $existingPermissions);

echo "==============================================\n";
echo "  HASIL ANALISIS\n";
echo "==============================================\n\n";

echo "✓ Permissions yang sudah ada: " . count($existingInBoth) . "\n";
echo "⚠ Permissions yang belum ada: " . count($missingPermissions) . "\n\n";

if (count($missingPermissions) > 0) {
    echo "==============================================\n";
    echo "  PERMISSIONS YANG AKAN DITAMBAHKAN\n";
    echo "==============================================\n\n";
    
    foreach ($missingPermissions as $index => $permission) {
        echo ($index + 1) . ". " . $permission . "\n";
    }
    
    echo "\n";
    
    $confirm = 'n';
    
    if ($dryRun) {
        echo "🔍 DRY RUN: Permissions di atas AKAN ditambahkan jika dijalankan tanpa --dry-run\n";
    } elseif ($autoMode) {
        echo "🤖 AUTO MODE: Menambahkan permissions secara otomatis...\n";
        $confirm = 'y';
    } else {
        echo "Apakah Anda ingin menambahkan " . count($missingPermissions) . " permissions ini? (y/n): ";
        
        $handle = fopen("php://stdin", "r");
        $line = fgets($handle);
        $confirm = trim(strtolower($line));
        fclose($handle);
    }
    
    if ($confirm === 'y' || $confirm === 'yes') {
        if (!$dryRun) {
            echo "\nMemulai insert permissions...\n\n";
            
            $inserted = 0;
            $failed = 0;
            
            foreach ($missingPermissions as $permission) {
                try {
                    DB::table('permissions')->insert([
                        'name' => $permission,
                        'guard_name' => 'web',
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                    
                    echo "✓ Inserted: " . $permission . "\n";
                    $inserted++;
                } catch (\Exception $e) {
                    echo "✗ Failed: " . $permission . " - " . $e->getMessage() . "\n";
                    $failed++;
                }
            }
            
            echo "\n==============================================\n";
            echo "  HASIL INSERT\n";
            echo "==============================================\n\n";
            echo "✓ Berhasil ditambahkan: " . $inserted . "\n";
            
            if ($failed > 0) {
                echo "✗ Gagal ditambahkan: " . $failed . "\n";
            }
            
            echo "\n✓ Proses selesai!\n";
        }
    } else {
        echo "\nProses dibatalkan.\n";
    }
} else {
    echo "✓ Semua permissions sudah sinkron!\n";
    echo "✓ Tidak ada permission yang perlu ditambahkan.\n";
}

// Cek permissions di database yang tidak ada di routes (orphaned permissions)
$orphanedPermissions = array_diff($existingPermissions, $routeNames);

if (count($orphanedPermissions) > 0) {
    echo "\n==============================================\n";
    echo "  INFO: PERMISSIONS DI DATABASE\n";
    echo "==============================================\n\n";
    echo "ℹ️  Ditemukan " . count($orphanedPermissions) . " permissions di database yang tidak ada di routes:\n\n";
    
    // Tampilkan hanya 10 pertama untuk tidak terlalu panjang
    $displayCount = min(10, count($orphanedPermissions));
    $orphanedArray = array_values($orphanedPermissions);
    
    for ($i = 0; $i < $displayCount; $i++) {
        echo ($i + 1) . ". " . $orphanedArray[$i] . "\n";
    }
    
    if (count($orphanedPermissions) > 10) {
        echo "... dan " . (count($orphanedPermissions) - 10) . " lainnya\n";
    }
    
    echo "\nCatatan: Permissions ini tetap ada di database dan tidak akan dihapus.\n";
    echo "Script ini hanya menambahkan permissions baru, tidak menghapus yang sudah ada.\n";
}

// Tampilkan statistik akhir
if (!$dryRun && isset($inserted)) {
    echo "\n==============================================\n";
    echo "  STATISTIK AKHIR\n";
    echo "==============================================\n\n";

    $finalPermissions = DB::table('permissions')->count();
    echo "Total permissions di database: " . $finalPermissions . "\n";
    echo "Total routes dengan nama: " . count($routeNames) . "\n";
    echo "Permissions yang sudah ada: " . count($existingInBoth) . "\n";
    
    if ($inserted > 0) {
        echo "Permissions baru ditambahkan: " . $inserted . "\n";
    }
}

echo "\n==============================================\n";
echo "  SELESAI\n";
echo "==============================================\n";
