<?php

use App\Http\Controllers\BrandController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\DirectSalesController;
use App\Http\Controllers\MobileModelController;
use App\Http\Controllers\PermissionController;
use App\Http\Controllers\PlanController;
use App\Http\Controllers\PosController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\SellTransactionController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\SubscriptionController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\TotalReportController;
use App\Http\Controllers\AllReportController;
use App\Http\Controllers\ExpenseController;
use App\Http\Controllers\ProfitReportController;
use App\Http\Controllers\SaleController;
use App\Http\Controllers\JobSheetController;

Route::get('/', function () {
    if (auth()->check()) {
        return redirect()->route('dashboard');
    }
    return redirect()->route('login');
})->name('home');

Route::get('/register', [App\Http\Controllers\Auth\RegisterController::class, 'showRegistrationForm'])->name('register');
Route::post('/register', [App\Http\Controllers\Auth\RegisterController::class, 'register']);
Route::get('/login', [App\Http\Controllers\Auth\LoginController::class, 'showLoginForm'])->name('login');
Route::post('/login', [App\Http\Controllers\Auth\LoginController::class, 'login']);
Route::get('/logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout.get');
Route::post('/logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout');

// Public routes (no authentication required)
Route::get('/sales/{id}/table-invoice', [SaleController::class, 'publicTableInvoice'])->name('sales.table.invoice.public');

Route::middleware(['auth', 'tenant'])->group(function () {
    Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/due-amount', [App\Http\Controllers\DashboardController::class, 'getDueAmountByDateRange'])->name('dashboard.due-amount');

    // System Update Routes
    Route::get('/system-update', [App\Http\Controllers\SystemUpdateController::class, 'index'])->name('system.update');
    Route::post('/system-update/perform', [App\Http\Controllers\SystemUpdateController::class, 'update'])->name('system.update.perform');
    Route::get('/system-update/changelog', [App\Http\Controllers\SystemUpdateController::class, 'changelog'])->name('system.update.changelog');

    Route::middleware(['permission:manage users'])->group(function () {
        Route::resource('users', App\Http\Controllers\UserController::class);
        Route::resource('roles', RoleController::class);
        Route::resource('permissions', PermissionController::class);
        Route::resource('plans', PlanController::class);
        Route::post('subscriptions/{id}/approve', [SubscriptionController::class, 'approve'])->name('subscriptions.approve');
        Route::resource('tenants', \App\Http\Controllers\TenantController::class);
    });

    // Subscriptions with custom permissions
    Route::resource('subscriptions', SubscriptionController::class);

    Route::get('/subscription', [App\Http\Controllers\SubscriptionController::class, 'show'])->name('subscription.show');
    Route::post('/subscription/subscribe', [App\Http\Controllers\SubscriptionController::class, 'subscribe'])->name('subscription.subscribe');
    Route::post('/subscription/cancel', [App\Http\Controllers\SubscriptionController::class, 'cancel'])->name('subscription.cancel');
    Route::post('/subscription/resume', [App\Http\Controllers\SubscriptionController::class, 'resume'])->name('subscription.resume');

    Route::get('pos', function () {
        return view('pos');
    });

Route::get('product/stock', [ProductController::class, 'product_stock'])->name('product.stock');
Route::get('product/stock-report', [ProductController::class, 'stockReport'])->name('product.stock.report');
Route::get('/product/{id}/print', [ProductController::class, 'print_receipt'])->name('product.print');    Route::post('product/direct-add', [ProductController::class, 'directAdd'])->name('product.directAdd');
    Route::get('products/search', [ProductController::class, 'searchProducts'])->name('product.search');
    Route::post('products/update-stock', [ProductController::class, 'updateStock'])->name('product.updateStock');
    Route::delete('products/bulk-delete', [ProductController::class, 'bulkDelete'])->name('product.bulkDelete');
    Route::get('products/test', function() { return view('product.test'); })->name('product.test');
    // Simple edit routes for name, price, stock only
    Route::get('product/{product}/edit-simple', [ProductController::class, 'editSimple'])->name('product.editSimple');
    Route::put('product/{product}/update-simple', [ProductController::class, 'updateSimple'])->name('product.updateSimple');
    Route::resource('product', ProductController::class);

    // Debug route for products Ajax - bypass auth
    Route::get('/debug-products-simple', function() {
        try {
            $products = \App\Models\Product::limit(5)->get();
            return response()->json([
                'success' => true,
                'products_count' => $products->count(),
                'products' => $products->toArray()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    });

    // Test Ajax endpoint like DataTables would call
    Route::get('/test-product-ajax', function(\Illuminate\Http\Request $request) {
        try {
            $tenant = app('tenant');
            $products = \App\Models\Product::where('tenant_id', $tenant->id)->get();
            
            $data = [];
            foreach ($products as $index => $product) {
                $data[] = [
                    'id' => $product->id,
                    'name' => $product->name ?? 'N/A',
                    'brand' => $product->brand ?? 'N/A',
                    'model' => $product->model ?? 'N/A',
                    'type' => $product->type ?? 'N/A',
                    'stock' => $product->stock ?? 0,
                    'condition' => $product->condition ?? 'N/A'
                ];
            }
            
            return response()->json([
                'draw' => $request->get('draw', 1),
                'recordsTotal' => $products->count(),
                'recordsFiltered' => $products->count(),
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 500);
        }
    });

    Route::get('pos', [PosController::class, 'index'])->name('pos.index');
    Route::post('fetch-pos-profit', [PosController::class, 'fetchProfit'])->name('pos.fetch.profit');


    Route::resource('customer', CustomerController::class);
    // Additional customer routes
    Route::get('/customers', [CustomerController::class, 'index'])->name('customers.index');
    Route::get('/customers/{id}', [CustomerController::class, 'show'])->name('customers.show');
    Route::get('/customers/list', [CustomerController::class, 'list'])->name('customer.list');
    Route::get('/customers/search', [CustomerController::class, 'search'])->name('customer.search');
    Route::post('/customers/check-phone', [CustomerController::class, 'checkPhone'])->name('customer.checkPhone');
    Route::post('/customers/pay-due', [CustomerController::class, 'payDue'])->name('customer.payDue');
    Route::resource('brand', BrandController::class);


    Route::get('/sell/{id}', [SellTransactionController::class, 'showSaleForm'])->name('sell.form');
    Route::post('/sell/{id}', [SellTransactionController::class, 'processSale'])->name('sell.process');
    Route::get('/sale/{id}', [SellTransactionController::class, 'saleInvoice'])->name('sale.invoice');
    Route::resource('sale', SellTransactionController::class);
    Route::get('sales-profit-report', [SellTransactionController::class, 'salesProfitReport'])->name('sales.profit.report');

    Route::resource('direct-sales', DirectSalesController::class);
    Route::get('direct-sale/invoice/{id}', [DirectSalesController::class, 'directSaleInvoice'])->name('direct-sales.invoice');

    Route::resource('settings', SettingController::class);

    Route::get('/admin/report', [ReportController::class, 'showReport'])->name('admin.report');



    Route::get('/report/totalreport', [TotalReportController::class, 'showReport'])->name('report.total.report');

    Route::get('/report', [AllReportController::class, 'index'])->name('report.index');
    Route::get('/profit-loss-report', [AllReportController::class, 'profitLoss'])->name('report.profit.loss');
    Route::post('/direct-product-store', [ProductController::class, 'storeDirectProduct'])->name('product.direct.store');
    Route::get('/settings/company-view', [SettingController::class, 'companyView'])->name('settings.companyview');
    Route::get('/invoice', [SettingController::class, 'showInvoice']);
    Route::get('/expense/report', [ExpenseController::class, 'report'])->name('expenses.report');
    Route::resource('categories', ExpenseController::class);
    Route::resource('expenses', ExpenseController::class);

    // Route::get('/profit-report', [ProfitReportController::class, 'generateReport']);

    // routes/web.php

    Route::get('/netreport', [ReportController::class, 'showReport'])->name('report.netprofit');

    Route::get('/customers/credits', [CustomerController::class, 'credits'])->name('customers.credits');

    // Routes for customers

    Route::get('/sales', [SaleController::class, 'index'])->name('sales.index');
    Route::get('/sales/create', [SaleController::class, 'create'])->name('sales.create');
    Route::post('/sales', [SaleController::class, 'store'])->name('sales.store');
    Route::get('/sales/{sale}/edit', [SaleController::class, 'edit'])->name('sales.edit');
    Route::put('/sales/{sale}', [SaleController::class, 'update'])->name('sales.update');
    Route::get('/sales/history', [SaleController::class, 'history'])->name('sales.history');
    Route::get('/sales/{id}/items', [SaleController::class, 'getItems'])->name('sales.items');
    Route::get('/sales/{id}/ajax-invoice', [SaleController::class, 'ajaxInvoice'])->name('sales.ajax.invoice');
    Route::get('/sales/{id}', [SaleController::class, 'show'])->name('sales.show');
    Route::post('/sales/{id}/mark-paid', [SaleController::class, 'markAsPaid'])->name('sales.mark.paid');
    Route::delete('/sales/{id}', [SaleController::class, 'destroy'])->name('sales.destroy');

    // Test route for debugging
    Route::get('/test-products-ajax', function() {
        $tenant = app('tenant');
        $totalRecords = \App\Models\Product::where('tenant_id', $tenant->id)->count();
        $totalPhones = \App\Models\Product::where('tenant_id', $tenant->id)->where('type', 'Phone')->count();
        $totalAccessories = \App\Models\Product::where('tenant_id', $tenant->id)->where('type', 'Accessories')->count();
        
        return response()->json([
            'recordsTotal' => $totalRecords,
            'totalPhones' => $totalPhones,
            'totalAccessories' => $totalAccessories,
            'debug' => 'Test successful'
        ]);
    });

    // Route::post('/sales/complete', [SalesController::class, 'complete'])->name('sales.complete');

    Route::prefix('pos')->group(function () {
        // Route to display the POS page (select customer, select product, etc.)
        Route::get('/create', [SaleController::class, 'create'])->name('pos.create');

        // Route to store the sale (process payment, update stock, generate invoice)
        Route::post('/store', [SaleController::class, 'store'])->name('pos.store');

        // Route to view the invoice after the sale is completed
        Route::get('/invoice/{id}', [SaleController::class, 'invoice'])->name('pos.invoice');
    });

    // routes/web.php

    Route::put('/jobsheet/{id}/update-status', [JobSheetController::class, 'updateStatus'])->name('jobsheet.updateStatus');
    Route::get('/jobsheet/report', [App\Http\Controllers\JobSheetController::class, 'showReport'])->name('jobsheet.report');
    Route::get('/jobsheet/invoice/{id}', [JobSheetController::class, 'invoice'])->name('jobsheet.invoice');
    Route::resource('jobsheet', JobSheetController::class);
    Route::get('/jobsheet/receipt/{id}', [JobSheetController::class, 'receipt'])->name('jobsheet.receipt');



    Route::get('/pos/dashboard', [PosController::class, 'dashboard'])->name('pos.dashboard');
    Route::get('/pos/customer-due', [PosController::class, 'getCustomerDue'])->name('pos.customer.due');
    Route::get('/pos/models-by-brand', [PosController::class, 'getModelsByBrand'])->name('pos.models.by.brand');
    Route::post('/sell', [PosController::class, 'store'])->name('sell.store');

    Route::resource('brands', BrandController::class);
    Route::resource('mobile-models', MobileModelController::class);

    // Invoice Settings Routes
    Route::get('/invoice-settings', [App\Http\Controllers\InvoiceSettingsController::class, 'index'])->name('invoice-settings.index');
    Route::put('/invoice-settings', [App\Http\Controllers\InvoiceSettingsController::class, 'update'])->name('invoice-settings.update');
    Route::get('/invoice-settings/preview', [App\Http\Controllers\InvoiceSettingsController::class, 'preview'])->name('invoice-settings.preview');
    Route::get('/invoice-settings/reset-defaults', [App\Http\Controllers\InvoiceSettingsController::class, 'resetDefaults'])->name('invoice-settings.reset-defaults');
    
    // WhatsApp Management Routes
    Route::get('/whatsapp/management', [App\Http\Controllers\InvoiceSettingsController::class, 'whatsappManagement'])->name('whatsapp.management');
    Route::get('/whatsapp/web-connect', [App\Http\Controllers\InvoiceSettingsController::class, 'webConnect'])->name('whatsapp.web.connect');
    Route::get('/whatsapp/connect', [App\Http\Controllers\InvoiceSettingsController::class, 'whatsappConnect'])->name('whatsapp.connect');
    Route::get('/whatsapp/check-connection', [App\Http\Controllers\InvoiceSettingsController::class, 'checkWhatsAppConnection'])->name('whatsapp.check.connection');
    Route::post('/whatsapp/send-test', [App\Http\Controllers\InvoiceSettingsController::class, 'sendTestMessage'])->name('whatsapp.send.test');
    Route::post('/whatsapp/disconnect', [App\Http\Controllers\InvoiceSettingsController::class, 'disconnectWhatsApp'])->name('whatsapp.disconnect');
    Route::post('/whatsapp/send-invoice', [App\Http\Controllers\InvoiceSettingsController::class, 'sendInvoiceMessage'])->name('whatsapp.send.invoice');
    Route::post('/whatsapp/generate-qr', [App\Http\Controllers\InvoiceSettingsController::class, 'generateWhatsAppQr'])->name('whatsapp.generate.qr');
    
    // Test route for phone formatting
    Route::get('/test-whatsapp-phone/{phone}', function($phone) {
        $whatsappService = new \App\Services\WhatsAppService();
        $formatted = $whatsappService->formatPhoneNumber($phone);
        
        $tenant = app('tenant');
        $settings = \App\Models\Setting::where('tenant_id', $tenant->id)->first();
        
        return response()->json([
            'original' => $phone,
            'formatted' => $formatted,
            'current_country_code' => $settings->whatsapp_country_code ?? 'not set',
            'auto_format_enabled' => $settings->whatsapp_auto_format_numbers ?? false,
            'settings_available' => $settings ? 'yes' : 'no'
        ]);
    });
    
    // Test route for direct phone formatting
    Route::get('/test-format-phone/{phone}', function($phone) {
        $whatsappService = new \App\Services\WhatsAppService();
        $tenant = app('tenant');
        $settings = \App\Models\Setting::where('tenant_id', $tenant->id)->first();
        
        $formatted = $whatsappService->formatPhoneNumber($phone);
        $whatsappData = $whatsappService->createInvoiceWhatsApp($phone, [
            'customer_name' => 'Test Customer',
            'customer_phone' => $phone,
            'invoice_number' => 'TEST-001',
            'total_amount' => '100.00',
            'currency' => 'BDT'
        ]);
        
        return response()->json([
            'original' => $phone,
            'formatted' => $formatted,
            'whatsapp_data_phone' => $whatsappData['phone'],
            'whatsapp_url' => $whatsappData['whatsapp_url'],
            'current_country_code' => $settings->whatsapp_country_code ?? 'not set',
            'auto_format_enabled' => $settings->whatsapp_auto_format_numbers ?? false,
            'settings_available' => $settings ? 'yes' : 'no'
        ]);
    });
    
    // Quick route to update country code for testing
    Route::get('/update-country-code/{code}', function($code) {
        $tenant = app('tenant');
        $settings = \App\Models\Setting::where('tenant_id', $tenant->id)->first();
        
        if (!$settings) {
            $settings = new \App\Models\Setting([
                'tenant_id' => $tenant->id,
                'currency' => 'BHD',
                'company_name' => 'Your Company Name'
            ]);
        }
        
        $settings->whatsapp_country_code = $code;
        $settings->whatsapp_auto_format_numbers = true;
        $settings->save();
        
        return response()->json([
            'success' => true,
            'message' => "Country code updated to {$code}",
            'new_code' => $settings->whatsapp_country_code
        ]);
    });
});
