<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DocumentationController;
use App\Http\Controllers\GrapeVarietyController;
use App\Http\Controllers\VarietyVariationController;
use App\Http\Controllers\VineyardMapController;
use App\Http\Controllers\PlantController;
use App\Http\Controllers\PlannedTaskController;
use App\Http\Controllers\VineyardOverviewController;
use App\Http\Controllers\VineyardRowController;
use App\Http\Controllers\HarvestController;
use App\Http\Controllers\WineController;
use App\Http\Controllers\WineProductionController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\CartController;
use App\Http\Controllers\PurchaseController;

// Landing page - About Us
Route::get('/', function () {
    return view('about');
})->name('about');

// Public docs
Route::get('/doc.html', [DocumentationController::class, 'show'])->name('docs.show');

// Contact page
Route::get('/contact', function () {
    return view('contact');
})->name('contact');

Route::post('/contact', function (\Illuminate\Http\Request $request) {
    $validated = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|max:255',
        'phone' => 'nullable|string|max:50',
        'subject' => 'required|string|max:255',
        'message' => 'required|string|max:2000',
    ]);

    // Here you could send an email or store in database
    // For now, we'll just return a success message
    // Example: Mail::to('info@winery.com')->send(new ContactMessage($validated));

    return redirect()->route('contact')->with('contact_success', 'Thank you for your message! We will get back to you soon.');
})->name('contact.send');

// Simple login view for frontend work (no auth logic)
Route::get('/login', function () {
    return view('auth.login');
})->name('login');

// Login POST handler
Route::post('/login', [LoginController::class, 'store'])->name('login.attempt');

// Registration (create account)
Route::get('/register', [RegisterController::class, 'create'])->name('register');
Route::post('/register', [RegisterController::class, 'store'])->name('register.store');

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

// Catalog routes (accessible to guests and authenticated users)
Route::get('/catalog', [WineController::class, 'catalog'])->name('catalog.index');
Route::get('/catalog/wines/{id}', [WineController::class, 'show'])->name('catalog.show');

// Events routes (accessible to guests and authenticated users)
Route::get('/events', [App\Http\Controllers\EventController::class, 'index'])->name('events.index');
Route::get('/events/{event}', [App\Http\Controllers\EventController::class, 'show'])->name('events.show');

// Cart routes (accessible to guests for browsing, but checkout requires auth)
Route::get('/cart', [CartController::class, 'index'])->name('cart.index');
Route::post('/cart/add/{wineId}', [CartController::class, 'add'])->name('cart.add');
Route::patch('/cart/update/{wineId}', [CartController::class, 'update'])->name('cart.update');
Route::delete('/cart/remove/{wineId}', [CartController::class, 'remove'])->name('cart.remove');
Route::delete('/cart/clear', [CartController::class, 'clear'])->name('cart.clear');
Route::get('/cart/count', [CartController::class, 'count'])->name('cart.count');

// Resource routes for winery management
Route::middleware(['auth'])->group(function () {
    // Dashboard
    Route::get('/dashboard', function () {
        $user = Auth::user();
        $plannedTasks = \App\Models\PlannedTask::with(['taskable'])
            ->whereNull('execution_date')
            ->where('planned_date', '>=', now()->subDays(7))
            ->where('planned_date', '<=', now()->addDays(7))
            ->orderBy('planned_date')
            ->get();

        $recentTasks = \App\Models\PlannedTask::with(['taskable'])
            ->whereNotNull('execution_date')
            ->orderBy('execution_date', 'desc')
            ->limit(5)
            ->get();

        return view('dashboard', compact('plannedTasks', 'recentTasks'));
    })->name('dashboard');

    // Purchase and checkout routes (require authentication)
    Route::post('/checkout', [PurchaseController::class, 'checkout'])->name('checkout');
    Route::get('/my-purchases', [PurchaseController::class, 'myPurchases'])->name('purchases.my');

    // Event reservations (require authentication)
    Route::post('/events/{event}/reserve', [App\Http\Controllers\EventController::class, 'reserve'])->name('events.reserve');
    Route::post('/events/{event}/cancel', [App\Http\Controllers\EventController::class, 'cancelReservation'])->name('events.cancel');
    Route::get('/my-reservations', [App\Http\Controllers\EventController::class, 'myReservations'])->name('events.my-reservations');

    Route::middleware('role:winemaker')->group(function () {
        Route::get('/vineyard/map', [VineyardMapController::class, 'index'])->name('vineyard.map');
        Route::get('/vineyard/map/edit', [VineyardMapController::class, 'edit'])->name('vineyard.map.edit');
        Route::get('/vineyard/add-plants', [PlantController::class, 'showAddForm'])->name('vineyard.addPlants');
        Route::post('/vineyard/add-plants/assign', [PlantController::class, 'assignToRows'])->name('vineyard.assignPlants');

        // API-style endpoint for creating variations from add-plants, using web guard like planning forms
        Route::post('/api/variety-variations/create-if-missing', [\App\Http\Controllers\Api\VarietyController::class, 'createIfMissing'])
            ->name('api.variety-variations.create');

        Route::get('/plan/watering', [PlannedTaskController::class, 'showWateringForm'])->name('plan.watering');
        Route::get('/plan/pruning', [PlannedTaskController::class, 'showPruningForm'])->name('plan.pruning');
        Route::get('/plan/fertilisation', [PlannedTaskController::class, 'showFertilisationForm'])->name('plan.fertilisation');
        Route::get('/plan/pesticide', [PlannedTaskController::class, 'showPesticideForm'])->name('plan.pesticide');
        Route::get('/plan/harvest', [PlannedTaskController::class, 'showHarvestForm'])->name('plan.harvest');
        Route::post('/planned-tasks/bulk', [PlannedTaskController::class, 'storeBulk'])->name('plannedtasks.storeBulk');
        Route::get('/planned-tasks/{task}/edit', [PlannedTaskController::class, 'edit'])->name('planned-tasks.edit');
        Route::put('/planned-tasks/{task}', [PlannedTaskController::class, 'update'])->name('planned-tasks.update');
        Route::delete('/planned-tasks/{task}', [PlannedTaskController::class, 'destroy'])->name('planned-tasks.destroy');

        Route::post('/vineyard/rows/update-headcount', [VineyardRowController::class, 'updateHeadCount'])->name('vineyard.updateHeadCount');
        Route::post('/vineyard/rows/add', [VineyardRowController::class, 'addRows'])->name('vineyard.addRows');
        Route::post('/vineyard/rows/discard', [VineyardRowController::class, 'discard'])->name('vineyard.rows.discard');
        Route::post('/vineyard/rows/delete-many', [VineyardRowController::class, 'destroyMany'])->name('vineyard.rows.destroyMany');
        Route::delete('/vineyard/rows/{vineyardRow}', [VineyardRowController::class, 'destroy'])->name('vineyard.rows.destroy');

        Route::get('/vineyard/overview', [VineyardOverviewController::class, 'index'])->name('vineyard.overview');
    });

    // Winemaker routes (restricted to winemaker role)
    Route::prefix('winemaker')->name('winemaker.')->middleware('role:winemaker')->group(function () {
        // Dashboard
        Route::get('/planned-tasks', [App\Http\Controllers\WinemakerController::class, 'allPlannedTasks'])->name('planned-tasks');
        Route::get('/completed-activities', [App\Http\Controllers\WinemakerController::class, 'allCompletedActivities'])->name('completed-activities');
        Route::get('/dashboard', [App\Http\Controllers\WinemakerController::class, 'dashboard'])->name('dashboard');

        // Harvest management
        Route::get('/harvests', [HarvestController::class, 'winemakerIndex'])->name('harvests.index');
        Route::get('/harvests/{id}/bottle', [HarvestController::class, 'bottleForm'])->name('harvests.bottle');
        Route::post('/harvests/bottle', [HarvestController::class, 'bottleStore'])->name('harvests.bottle.store');
        Route::delete('/harvests/{harvest}', [HarvestController::class, 'destroy'])->name('harvests.destroy');

        // Cellar management
        Route::get('/cellar', [WineController::class, 'cellarIndex'])->name('cellar.index');
        Route::get('/cellar/create-blend', [WineController::class, 'createBlendForm'])->name('cellar.blend.create');
        Route::post('/cellar/create-blend', [WineController::class, 'storeBlend'])->name('cellar.blend.store');

        // Sales management
        Route::get('/sales', [WineController::class, 'salesIndex'])->name('sales.index');
        Route::post('/wines/{id}/add-to-sales', [WineController::class, 'addToSales'])->name('wines.add-to-sales');
        Route::post('/wines/{id}/remove-from-sales', [WineController::class, 'removeFromSales'])->name('wines.remove-from-sales');
    });

    // Legacy cellar routes (kept for backward compatibility, restricted to winemaker role)
    Route::middleware('role:winemaker')->group(function () {
        Route::get('/cellar/wines', [WineController::class, 'cellarIndex'])->name('cellar.wines');
        Route::get('/cellar/wines/sales', [WineController::class, 'salesIndex'])->name('cellar.sales');
        Route::post('/cellar/wines/{id}/add-to-sales', [WineController::class, 'addToSales'])->name('cellar.addToSales');
    });

    // Resource routes (restricted to winemaker role)
    Route::middleware('role:winemaker')->group(function () {
        Route::resource('grape-varieties', GrapeVarietyController::class);
        Route::resource('variety-variations', VarietyVariationController::class);
        Route::resource('vineyard-rows', VineyardRowController::class);
        Route::resource('harvests', HarvestController::class);
        Route::resource('wines', WineController::class);
        Route::resource('wine-productions', WineProductionController::class);
    });

    // Admin routes (restricted to admin role)
    Route::prefix('admin')->name('admin.')->middleware('admin')->group(function () {
        Route::get('/users', [App\Http\Controllers\Admin\UserController::class, 'index'])->name('users.index');
        Route::get('/users/create', [App\Http\Controllers\Admin\UserController::class, 'create'])->name('users.create');
        Route::post('/users', [App\Http\Controllers\Admin\UserController::class, 'store'])->name('users.store');
        Route::get('/users/{user}/edit', [App\Http\Controllers\Admin\UserController::class, 'edit'])->name('users.edit');
        Route::put('/users/{user}', [App\Http\Controllers\Admin\UserController::class, 'update'])->name('users.update');
        Route::delete('/users/{user}', [App\Http\Controllers\Admin\UserController::class, 'destroy'])->name('users.destroy');
        
        // Event management
        Route::get('/events', [App\Http\Controllers\Admin\EventController::class, 'index'])->name('events.index');
        Route::get('/events/create', [App\Http\Controllers\Admin\EventController::class, 'create'])->name('events.create');
        Route::post('/events', [App\Http\Controllers\Admin\EventController::class, 'store'])->name('events.store');
        Route::get('/events/{event}/edit', [App\Http\Controllers\Admin\EventController::class, 'edit'])->name('events.edit');
        Route::put('/events/{event}', [App\Http\Controllers\Admin\EventController::class, 'update'])->name('events.update');
        Route::delete('/events/{event}', [App\Http\Controllers\Admin\EventController::class, 'destroy'])->name('events.destroy');
    });

    // Employee routes (restricted to employee and admin roles)
    Route::prefix('employee')->name('employee.')->middleware('employee')->group(function () {
        Route::get('/tasks', [App\Http\Controllers\Employee\TaskController::class, 'index'])->name('tasks.index');
        Route::patch('/tasks/{task}/complete-treatment', [App\Http\Controllers\Employee\TaskController::class, 'completeTreatment'])->name('tasks.complete-treatment');
        Route::patch('/tasks/{task}/complete-harvest', [App\Http\Controllers\Employee\TaskController::class, 'completeHarvest'])->name('tasks.complete-harvest');
    });
});
