<?php

use App\Http\Controllers\AuthController;
use App\Http\Controllers\DashboardController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes — SPPG Terpadu (Dapur Wiki + Data Sekolah)
|--------------------------------------------------------------------------
*/

use App\Http\Controllers\MasterDataController;
use App\Http\Controllers\HargaPasarController;
use App\Http\Controllers\SuplierController;
use App\Http\Controllers\HargaRealController;
use App\Http\Controllers\BankMenuController;
use App\Http\Controllers\PurchaseOrderController;
use App\Http\Controllers\UserManagementController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\BarangOperasionalController;
use App\Http\Controllers\DataSekolahController;
use App\Http\Controllers\DataSiswaController;

use App\Http\Controllers\DataPosyanduController;
use App\Http\Controllers\DataSasaranController;

// === AUTH (dengan login throttle) ===
Route::get('/login', [AuthController::class, 'showLogin'])->name('login');
Route::post('/login', [AuthController::class, 'login'])->middleware('throttle:login');
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

// === SETUP DATABASE (Cpanel / Hosting Deployer) ===
// Dilindungi oleh SETUP_TOKEN, aman untuk production.
Route::get('/setup-database', function (\Illuminate\Http\Request $request) {
    $token = env('SETUP_TOKEN', 'dapurwiki2026');
    if ($request->query('token') !== $token) {
        return response('Unauthorized. Token tidak valid.', 401);
    }
    try {
        // Override driver ke array/sync agar tidak butuh tabel session/cache
        config([
            'session.driver' => 'array',
            'cache.default' => 'array',
            'queue.default' => 'sync',
        ]);

        // Test koneksi DB dulu
        \Illuminate\Support\Facades\DB::connection()->getPdo();

        // Jalankan migrasi biasa (bukan fresh, agar data aman)
        \Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
        $output = \Illuminate\Support\Facades\Artisan::output();
        
        // Buat Storage Link
        try {
            \Illuminate\Support\Facades\Artisan::call('storage:link');
            $output .= "\n" . \Illuminate\Support\Facades\Artisan::output();
        } catch (\Exception $e) {
            $output .= "\nStorage Link Error (mungkin sudah ada): " . $e->getMessage();
        }

        return response('✅ Sukses! Tabel MySQL SPPG Terpadu dan Data Awal berhasil dibuat. Silakan login dengan superadmin / 123456.<br><br><pre>' . $output . '</pre>');
    } catch (\Exception $e) {
        return response('❌ Gagal: ' . $e->getMessage() . '<br><br>File: ' . $e->getFile() . ':' . $e->getLine(), 500);
    }
});

// === DIAGNOSTIC (cek konfigurasi hosting) ===
Route::get('/setup-check', function (\Illuminate\Http\Request $request) {
    $token = env('SETUP_TOKEN', 'dapurwiki2026');
    if ($request->query('token') !== $token) {
        return response('Unauthorized.', 401);
    }
    $checks = [];
    $checks['php_version'] = PHP_VERSION;
    $checks['laravel_base'] = base_path();
    $checks['public_path'] = public_path();
    $checks['storage_writable'] = is_writable(storage_path()) ? '✅ Ya' : '❌ Tidak';
    $checks['bootstrap_cache_writable'] = is_writable(base_path('bootstrap/cache')) ? '✅ Ya' : '❌ Tidak';
    $checks['env_exists'] = file_exists(base_path('.env')) ? '✅ Ya' : '❌ Tidak';
    $checks['app_key_set'] = !empty(env('APP_KEY')) ? '✅ Ya' : '❌ Tidak';
    $checks['db_connection'] = env('DB_CONNECTION', 'not set');
    $checks['db_database'] = env('DB_DATABASE', 'not set');
    $checks['session_driver'] = env('SESSION_DRIVER', 'not set');
    $checks['vendor_exists'] = file_exists(base_path('vendor/autoload.php')) ? '✅ Ya' : '❌ Tidak';

    try {
        \Illuminate\Support\Facades\DB::connection()->getPdo();
        $checks['db_connected'] = '✅ Terhubung';
    } catch (\Exception $e) {
        $checks['db_connected'] = '❌ Gagal: ' . $e->getMessage();
    }

    $html = "<h2>🔍 SPPG Terpadu — Diagnostic</h2><table border='1' cellpadding='8' style='border-collapse:collapse;font-family:monospace;'>";
    foreach ($checks as $key => $val) {
        $html .= "<tr><td><b>{$key}</b></td><td>{$val}</td></tr>";
    }
    $html .= "</table>";
    return response($html);
});

// === DASHBOARD (SPA Entry Point) ===
Route::middleware(['auth', 'check.masa.aktif'])->group(function () {
    Route::get('/', [DashboardController::class, 'index'])->name('dashboard');

    // === API ENDPOINTS (Rate Limited: 120 req/min) ===
    Route::prefix('api')->middleware('throttle:api')->group(function () {

        // === BATCH INITIAL DATA (single request replaces 8+ parallel calls) ===
        Route::get('initial-data', [DashboardController::class, 'initialData']);
        // === PROFILE ===
        Route::post('profile', [ProfileController::class, 'update']);

        // === MASTER DATA (Bahan Makanan + Kandungan Gizi) — Global, hanya Super Admin ===
        Route::get('master-data', [MasterDataController::class, 'index']);
        Route::post('master-data', [MasterDataController::class, 'store'])
            ->middleware('role:Super Admin');
        Route::delete('master-data/truncate', [MasterDataController::class, 'truncate'])
            ->middleware('role:Super Admin');
        Route::delete('master-data/{id}', [MasterDataController::class, 'destroy'])
            ->middleware('role:Super Admin');
        Route::post('master-data/import', [MasterDataController::class, 'import'])
            ->middleware('role:Super Admin');

        // === HARGA PASAR ===
        Route::get('harga-pasar', [HargaPasarController::class, 'index']);
        Route::post('harga-pasar', [HargaPasarController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Gizi');
        Route::delete('harga-pasar/{id}', [HargaPasarController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Gizi');
        Route::get('harga-pasar-history', [HargaPasarController::class, 'history']);
        Route::post('harga-pasar/import', [HargaPasarController::class, 'import'])
            ->middleware('role:Super Admin,PLO Gizi');

        // === SUPLIER ===
        Route::get('suplier', [SuplierController::class, 'index']);
        Route::post('suplier', [SuplierController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');
        Route::delete('suplier/{id}', [SuplierController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG');

        // === HARGA REAL (Nota Belanja) ===
        Route::get('harga-real', [HargaRealController::class, 'index']);
        Route::post('harga-real', [HargaRealController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');
        Route::delete('harga-real/{id}', [HargaRealController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');

        // === BANK MENU ===
        Route::get('bank-menu', [BankMenuController::class, 'index']);
        Route::post('bank-menu', [BankMenuController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Gizi');
        Route::delete('bank-menu/{id}', [BankMenuController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Gizi');

        // === PURCHASE ORDER ===
        Route::get('po', [PurchaseOrderController::class, 'index']);
        Route::post('po', [PurchaseOrderController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');
        Route::delete('po/{id}', [PurchaseOrderController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');

        // === BARANG OPERASIONAL ===
        Route::get('operasional', [BarangOperasionalController::class, 'index']);
        Route::post('operasional', [BarangOperasionalController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');
        Route::delete('operasional/{id}', [BarangOperasionalController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,PLO Keuangan');

        // === DAPUR ===
        Route::get('dapur', [UserManagementController::class, 'indexDapur']);
        Route::get('dapur-settings', [DashboardController::class, 'getDapurSettings']);
        Route::post('dapur-settings', [DashboardController::class, 'updateDapurSettings'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');

        // === USER MANAGEMENT (Super Admin Only) ===
        Route::middleware('role:Super Admin')->group(function () {
            Route::get('users', [UserManagementController::class, 'index']);
            Route::post('users', [UserManagementController::class, 'store']);
            Route::post('users/resend-email/{id}', [UserManagementController::class, 'resendEmail']);
            Route::delete('users/{id}', [UserManagementController::class, 'destroy']);
            Route::post('users/create-branch', [UserManagementController::class, 'createBranch']);
            Route::delete('users/delete-branch/{id}', [UserManagementController::class, 'destroyBranch']);
        });

        // =============================================
        // DATA SASARAN (Sekolah + Posyandu)
        // =============================================
        Route::get('dashboard-sasaran', [DataSasaranController::class, 'dashboardSummary']);
        Route::get('porsi-summary', [DataSasaranController::class, 'porsiSummary']);

        // === DATA SEKOLAH ===
        Route::get('data-sekolah', [DataSekolahController::class, 'index']);
        Route::post('data-sekolah', [DataSekolahController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-sekolah/{id}', [DataSekolahController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::get('data-sekolah/print-all', [DataSekolahController::class, 'printAll']);
        Route::get('data-sekolah/{id}/detail', [DataSekolahController::class, 'getDetail']);

        // === DATA PENERIMA MANFAAT (Siswa, Guru, Staf) ===
        Route::post('data-siswa', [DataSiswaController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-siswa/{id}', [DataSiswaController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::post('data-siswa/import', [DataSiswaController::class, 'import'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::post('data-siswa/promote/{idSekolah}', [DataSiswaController::class, 'promote'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::delete('data-siswa/truncate/{idSekolah}', [DataSiswaController::class, 'truncate'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::get('data-siswa/export/{idSekolah}', [DataSiswaController::class, 'export']);

        // === DATA POSYANDU ===
        Route::get('data-posyandu', [DataPosyanduController::class, 'index']);
        Route::post('data-posyandu', [DataPosyanduController::class, 'store'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-posyandu/{id}', [DataPosyanduController::class, 'destroy'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::get('data-posyandu/print-all', [DataPosyanduController::class, 'printAll']);
        Route::get('data-posyandu/{id}/detail', [DataPosyanduController::class, 'getDetail']);

        // === DATA BALITA ===
        Route::post('data-balita', [DataSasaranController::class, 'storeBalita'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-balita/{id}', [DataSasaranController::class, 'destroyBalita'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::post('data-balita/import', [DataSasaranController::class, 'importBalita'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-balita/truncate/{idPosyandu}', [DataSasaranController::class, 'truncateBalita'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');

        // === DATA IBU HAMIL ===
        Route::post('data-ibuhamil', [DataSasaranController::class, 'storeIbuHamil'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-ibuhamil/{id}', [DataSasaranController::class, 'destroyIbuHamil'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::post('data-ibuhamil/import', [DataSasaranController::class, 'importIbuHamil'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::post('data-ibuhamil/{id}/move-menyusui', [DataSasaranController::class, 'moveToMenyusui'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-ibuhamil/truncate/{idPosyandu}', [DataSasaranController::class, 'truncateIbuHamil'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');

        // === DATA IBU MENYUSUI ===
        Route::post('data-ibumenyusui', [DataSasaranController::class, 'storeIbuMenyusui'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-ibumenyusui/{id}', [DataSasaranController::class, 'destroyIbuMenyusui'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::post('data-ibumenyusui/{id}/toggle-status', [DataSasaranController::class, 'toggleStatusIbuMenyusui'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::post('data-ibumenyusui/import', [DataSasaranController::class, 'importIbuMenyusui'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-ibumenyusui/truncate/{idPosyandu}', [DataSasaranController::class, 'truncateIbuMenyusui'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');

        // === DATA KADER ===
        Route::post('data-kader', [DataSasaranController::class, 'storeKader'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-kader/{id}', [DataSasaranController::class, 'destroyKader'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');
        Route::post('data-kader/{id}/toggle-status', [DataSasaranController::class, 'toggleStatusKader'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::post('data-kader/import', [DataSasaranController::class, 'importKader'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('data-kader/truncate/{idPosyandu}', [DataSasaranController::class, 'truncateKader'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');

        // === ANTROPOMETRI ===
        Route::get('antropometri/{entityType}/{entityId}', [DataSasaranController::class, 'antropometriIndex']);
        Route::post('antropometri', [DataSasaranController::class, 'antropometriStore'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data,PLO Gizi');
        Route::delete('antropometri/{id}', [DataSasaranController::class, 'antropometriDestroy'])
            ->middleware('role:Super Admin,Kepala SPPG,Admin Data');

        // === TEMPLATES ===
        Route::get('template/{type}', [App\Http\Controllers\DashboardController::class, 'downloadTemplate']);
        Route::post('template/{type}', [App\Http\Controllers\DashboardController::class, 'uploadTemplate'])
            ->middleware('role:Super Admin');
    });
});
