<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

// ── Controllers User ──────────────────────────────────────────────
use App\Http\Controllers\AnalysisController;
use App\Http\Controllers\CompanyController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\HistoryController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\SearchController;
use App\Http\Controllers\NotificationsController;
use App\Http\Controllers\PageController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\Auth\SocialController;
use App\Http\Controllers\ContactController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\SubscriptionController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\SettingsController;


// ── Controllers Admin ─────────────────────────────────────────────
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\UserController as AdminUserController;
use App\Http\Controllers\Admin\AnalysisController as AdminAnalysisController;
use App\Http\Controllers\Admin\SettingsController as AdminSettingsController;
use App\Http\Controllers\Admin\ContactController as AdminContactController;

// ══════════════════════════════════════════════════════════════════
// HOME
// ══════════════════════════════════════════════════════════════════
Route::get('/', function () {
    return view('welcome');
})->name('home');

// ══════════════════════════════════════════════════════════════════
// PUBLIC PAGES
// ══════════════════════════════════════════════════════════════════
Route::name('public.')->group(function () {
    Route::get('/tentang',           [PageController::class, 'about'])->name('about');
    Route::get('/fitur',             [PageController::class, 'features'])->name('features');
    Route::get('/kontak',            [PageController::class, 'contact'])->name('contact');
    Route::post('/kontak',           [PageController::class, 'sendContact'])->name('contact.send');
    Route::get('/faq',               [PageController::class, 'faq'])->name('faq');
    Route::get('/panduan',           [PageController::class, 'guide'])->name('guide');
    Route::get('/kebijakan-privasi', [PageController::class, 'privacy'])->name('privacy');
    Route::get('/syarat-ketentuan',  [PageController::class, 'terms'])->name('terms');
});

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

// ══════════════════════════════════════════════════════════════════
// AUTH (Guest only)
// ══════════════════════════════════════════════════════════════════
Route::middleware('guest')->group(function () {
    Route::get('/login',  [LoginController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [LoginController::class, 'login']);

    Route::get('/register',  [RegisterController::class, 'showRegistrationForm'])->name('register');
    Route::post('/register', [RegisterController::class, 'register']);

    Route::get('/forgot-password', fn() => view('auth.forgot-password'))->name('password.request');
});

// Google OAuth — di luar middleware guest
Route::get('/auth/google',          [SocialController::class, 'redirectGoogle'])->name('auth.google');
Route::get('/auth/google/callback', [SocialController::class, 'callbackGoogle'])->name('auth.google.callback');

Route::post('/logout', [LoginController::class, 'logout'])->name('logout')->middleware('auth');

// ══════════════════════════════════════════════════════════════════
// DASHBOARD — admin redirect ke /admin
// ══════════════════════════════════════════════════════════════════
Route::middleware('auth')->group(function () {
    Route::get('/dashboard', function () {
        if (Auth::user()->isAdmin()) {
            return redirect()->route('admin.dashboard');
        }
        return app(DashboardController::class)->index(request());
    })->name('dashboard');

    Route::get('/dashboard/chart-data', [DashboardController::class, 'chartData'])->name('dashboard.chart');
    Route::get('/dashboard/export',     [DashboardController::class, 'export'])->name('dashboard.export');
});

// ══════════════════════════════════════════════════════════════════
// ANALYSIS
// ══════════════════════════════════════════════════════════════════
Route::prefix('analysis')->name('analysis.')->middleware('auth')->group(function () {
    Route::get('/step1',  [AnalysisController::class, 'step1'])->name('step1');
    Route::post('/step1', [AnalysisController::class, 'saveStep1'])->name('step1.save');
    Route::get('/step2',  [AnalysisController::class, 'step2'])->name('step2');
    Route::post('/step2', [AnalysisController::class, 'saveStep2'])->name('step2.save');
    Route::get('/result', [AnalysisController::class, 'result'])->name('result');
    Route::post('/reset', [AnalysisController::class, 'reset'])->name('reset');
});

// ══════════════════════════════════════════════════════════════════
// HISTORY
// ══════════════════════════════════════════════════════════════════
Route::prefix('history')->name('history.')->middleware('auth')->group(function () {
    Route::get('/',                    [HistoryController::class, 'index'])->name('index');
    Route::get('/{id}',               [HistoryController::class, 'show'])->name('show')->where('id', '[0-9]+');
    Route::delete('/{id}',            [HistoryController::class, 'destroy'])->name('destroy')->where('id', '[0-9]+');
    Route::post('/bulk-delete',        [HistoryController::class, 'bulkDestroy'])->name('bulk-destroy');
    Route::get('/compare/{id1}/{id2}', [HistoryController::class, 'compare'])->name('compare');
    Route::get('/export',              [HistoryController::class, 'export'])->name('export');
});

// ══════════════════════════════════════════════════════════════════
// COMPANIES
// ══════════════════════════════════════════════════════════════════
Route::prefix('companies')->name('companies.')->middleware('auth')->group(function () {
    Route::get('/',            [CompanyController::class, 'index'])->name('index');
    Route::get('/{name}',      [CompanyController::class, 'show'])->name('show');
    Route::get('/{name}/edit', [CompanyController::class, 'edit'])->name('edit');
    Route::put('/{name}',      [CompanyController::class, 'update'])->name('update');
    Route::delete('/{name}',   [CompanyController::class, 'destroy'])->name('destroy');
});

// ══════════════════════════════════════════════════════════════════
// REPORT
// ══════════════════════════════════════════════════════════════════
Route::prefix('report')->name('report.')->middleware('auth')->group(function () {
    Route::get('/{id}/download',  [ReportController::class, 'download'])->name('download')->where('id', '[0-9]+');
    Route::get('/{id}/preview',   [ReportController::class, 'preview'])->name('preview')->where('id', '[0-9]+');
    Route::post('/{id}/custom',   [ReportController::class, 'custom'])->name('custom');
    Route::post('/{id}/email',    [ReportController::class, 'email'])->name('email');
    Route::get('/{id}/metadata',  [ReportController::class, 'metadata'])->name('metadata');
    Route::get('/templates',      [ReportController::class, 'templates'])->name('templates');
    Route::post('/batch',         [ReportController::class, 'batch'])->name('batch');
    Route::post('/compare',       [ReportController::class, 'compare'])->name('compare');
});

// ══════════════════════════════════════════════════════════════════
// API (AJAX)
// ══════════════════════════════════════════════════════════════════
Route::prefix('api')->name('api.')->middleware('auth')->group(function () {
    Route::post('/calculate',               [AnalysisController::class, 'calculateAjax'])->name('calculate');
    Route::get('/search',                   [AnalysisController::class, 'search'])->name('search');
    Route::post('/analysis/{id}/favorite',  [AnalysisController::class, 'toggleFavorite'])->name('analysis.favorite');
    Route::post('/analysis/{id}/share',     [AnalysisController::class, 'share'])->name('analysis.share');
    Route::get('/notifications',            [NotificationsController::class, 'index'])->name('notifications');
    Route::post('/notifications/{id}/read', [NotificationsController::class, 'markAsRead'])->name('notifications.read');
});

// ══════════════════════════════════════════════════════════════════
// PROFILE & SETTINGS
// ══════════════════════════════════════════════════════════════════
Route::middleware('auth')->group(function () {
    Route::get('/profile',           [ProfileController::class, 'edit'])->name('profile.edit');
    Route::put('/profile',           [ProfileController::class, 'update'])->name('profile.update');
    Route::put('/profile/password',  [ProfileController::class, 'updatePassword'])->name('profile.password');
    Route::delete('/profile',        [ProfileController::class, 'destroy'])->name('profile.destroy');
    Route::get('/settings',          [SettingsController::class, 'index'])->name('settings');
    Route::put('/settings',          [SettingsController::class, 'update'])->name('settings.update');
});

// ══════════════════════════════════════════════════════════════════
// SUBSCRIPTION & PEMBAYARAN (Midtrans)
// ══════════════════════════════════════════════════════════════════

// Webhook — TANPA auth
Route::post('/subscription/notification', [SubscriptionController::class, 'notification'])
    ->name('subscription.notification');

// Semua route subscription butuh login
Route::middleware('auth')->prefix('subscription')->name('subscription.')->group(function () {

    Route::get('/',          [SubscriptionController::class, 'index'])->name('index');
    Route::get('/checkout',  [SubscriptionController::class, 'checkoutPage'])->name('checkout.page');
    Route::post('/checkout', [SubscriptionController::class, 'checkout'])->name('checkout');

    // ✅ Ini yang dipanggil welcome.blade.php lewat route('subscription.subscribe.pro')
    Route::post('/subscribe/pro', [SubscriptionController::class, 'createSubscription'])->name('subscribe.pro');

    Route::get('/payment/success', [SubscriptionController::class, 'paymentSuccess'])->name('payment.success');

    Route::get('/success',  [SubscriptionController::class, 'success'])->name('success');
    Route::get('/pending',  [SubscriptionController::class, 'pending'])->name('pending');
    Route::get('/failed',   [SubscriptionController::class, 'failed'])->name('failed');

    Route::get('/history',  [SubscriptionController::class, 'history'])->name('history');
    Route::post('/cancel',  [SubscriptionController::class, 'cancel'])->name('cancel');
});

Route::middleware('auth')->prefix('subscription')->name('subscription.')->group(function () {
    // ...
    Route::get('/subscribe/pro',  [SubscriptionController::class, 'confirmPro'])->name('confirm.pro');
    Route::post('/subscribe/pro', [SubscriptionController::class, 'createSubscription'])->name('subscribe.pro');
});

// ══════════════════════════════════════════════════════════════════
// ADMIN — hanya role = 'admin'
// ══════════════════════════════════════════════════════════════════
Route::prefix('admin')->name('admin.')->middleware(['auth', 'admin'])->group(function () {

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

    // Kelola User
    Route::prefix('users')->name('users.')->group(function () {
        Route::get('/',                    [AdminUserController::class, 'index'])->name('index');
        Route::get('/create',              [AdminUserController::class, 'create'])->name('create');
        Route::post('/',                   [AdminUserController::class, 'store'])->name('store');
        Route::get('/{id}',               [AdminUserController::class, 'show'])->name('show');
        Route::get('/{id}/edit',          [AdminUserController::class, 'edit'])->name('edit');
        Route::put('/{id}',               [AdminUserController::class, 'update'])->name('update');
        Route::delete('/{id}',            [AdminUserController::class, 'destroy'])->name('destroy');
        Route::post('/{id}/ban',          [AdminUserController::class, 'ban'])->name('ban');
        Route::post('/{id}/unban',        [AdminUserController::class, 'unban'])->name('unban');
        Route::post('/{id}/make-admin',   [AdminUserController::class, 'makeAdmin'])->name('make-admin');
        Route::post('/{id}/revoke-admin', [AdminUserController::class, 'revokeAdmin'])->name('revoke-admin');
    });

    // Semua Riwayat Analisis
    Route::prefix('analyses')->name('analyses.')->group(function () {
        Route::get('/',         [AdminAnalysisController::class, 'index'])->name('index');
        Route::get('/{id}',    [AdminAnalysisController::class, 'show'])->name('show');
        Route::delete('/{id}', [AdminAnalysisController::class, 'destroy'])->name('destroy');
    });

    // Pengaturan Global
    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/',        [AdminSettingsController::class, 'index'])->name('index');
        Route::put('/',        [AdminSettingsController::class, 'update'])->name('update');
        Route::post('/reset',  [AdminSettingsController::class, 'reset'])->name('reset');
    });

    // Payment token (legacy)
    Route::post('/payment/get-token/{package}', [PaymentController::class, 'getToken'])->name('payment.get-token');

    // Contacts Management
    Route::prefix('contacts')->name('contacts.')->group(function () {
        Route::get('/',              [AdminContactController::class, 'index'])->name('index');
        Route::get('/{id}',         [AdminContactController::class, 'show'])->name('show');
        Route::post('/{id}/reply',   [AdminContactController::class, 'reply'])->name('reply');
        Route::put('/{id}/status',   [AdminContactController::class, 'updateStatus'])->name('update-status');
        Route::delete('/{id}',       [AdminContactController::class, 'destroy'])->name('destroy');
        Route::delete('/bulk',       [AdminContactController::class, 'bulkDestroy'])->name('bulk-destroy');
        Route::get('/export/csv',    [AdminContactController::class, 'export'])->name('export');
    });
});
