<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\FormController;
use App\Http\Controllers\SubmissionController;
use App\Http\Controllers\InternalController;
use App\Http\Controllers\PasswordController; // <-- TAMBAHKAN INI
use App\Http\Controllers\DataEntryController;
use App\Http\Controllers\FieldConfigController;
use App\Http\Controllers\MonitoringController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Google\Client as GoogleClient;
use Google\Service\Drive as GoogleDrive;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// Halaman utama akan langsung diarahkan ke halaman login
Route::get('/', function () {
    return redirect('/login');
});

// Grup Rute Autentikasi
Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
// throttle: maks 8 percobaan/menit per IP (anti brute-force)
Route::post('/login', [LoginController::class, 'handleLogin'])->middleware('throttle:8,1');
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

// Grup Rute Admin (dijaga oleh middleware 'admin')
Route::prefix('admin')->middleware(['auth.custom', 'admin'])->group(function () {
    Route::get('/create-user', [AdminController::class, 'showCreateUserForm'])->name('admin.user.create');
    Route::post('/create-user', [AdminController::class, 'createUser']);
});

// Grup Rute Aplikasi Utama (setelah login)
Route::middleware('auth.custom')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'showDashboard'])->name('dashboard');

    Route::get('/form/{slugInstansi}', [FormController::class, 'showForm'])
        ->name('form.show')
        ->middleware('check.instansi');

    Route::post('/submit-data', [SubmissionController::class, 'store'])->name('data.store');
    Route::post('/upload-file', [SubmissionController::class, 'uploadFile'])->name('file.upload');
    Route::get('/preview-data/{slugInstansi}', [FormController::class, 'fetchPreviewData'])->name('preview.data');

    // --- FASE 2: input data lewat tabel (Supabase) + atur kolom via web ---
    Route::get('/data/{slug}', [DataEntryController::class, 'edit'])
        ->name('data.edit')->middleware('check.instansi');
    Route::post('/data/{slug}', [DataEntryController::class, 'save'])
        ->name('data.save')->middleware('check.instansi');

    // Atur kolom (khusus admin)
    Route::get('/data/{slug}/fields', [FieldConfigController::class, 'index'])
        ->name('data.fields')->middleware('admin');
    Route::post('/data/{slug}/fields', [FieldConfigController::class, 'store'])
        ->name('data.fields.store')->middleware('admin');
    Route::post('/data/{slug}/fields/delete', [FieldConfigController::class, 'destroy'])
        ->name('data.fields.delete')->middleware('admin');

    // Rute Internal (dijaga oleh middleware 'admin')
    Route::get('/internal', [InternalController::class, 'index'])
        ->name('internal.index')
        ->middleware('admin');
    Route::post('/internal/create-user', [InternalController::class, 'createUser'])
        ->name('internal.user.create')
        ->middleware('admin');

    Route::get('/monitoring', [MonitoringController::class, 'index'])->name('monitoring');

    // --- RUTE BARU UNTUK UBAH PASSWORD ---
    Route::get('/change-password', [PasswordController::class, 'showChangePasswordForm'])->name('password.change.form');
    Route::post('/change-password', [PasswordController::class, 'changePassword'])->name('password.change');
    // --- AKHIR RUTE BARU ---
});


// RUTE SEMENTARA UNTUK OTORISASI GOOGLE DRIVE (hanya aktif di local, TIDAK di produksi)
// Dipakai sekali untuk membuat gdrive_token.json. Dikunci ke environment lokal demi keamanan.
if (app()->environment('local')) {
    Route::get('/google-auth/generate-token', function () {
        $client = new GoogleClient();
        $client->setAuthConfig(storage_path('app/oauth_credentials.json'));
        $client->addScope(GoogleDrive::DRIVE);
        $client->setRedirectUri(route('google.callback'));
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');
        return redirect()->to($client->createAuthUrl());
    })->name('google.auth');

    Route::get('/google/callback', function (Request $request) {
        $client = new GoogleClient();
        $client->setAuthConfig(storage_path('app/oauth_credentials.json'));
        $client->setRedirectUri(route('google.callback'));
        $token = $client->fetchAccessTokenWithAuthCode($request->code);
        Storage::disk('local')->put('gdrive_token.json', json_encode($token));
        return 'Token berhasil dibuat! File gdrive_token.json telah disimpan di storage/app/.';
    })->name('google.callback');
}
