<?php


use App\Http\Controllers\Frontend\CartController;
use App\Http\Controllers\Frontend\Helpdesk\TicketsController;
use App\Mail\InstallationCompleteMail;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('clear', function () {
    Artisan::call('optimize:clear');
    dump(Artisan::output());
});

Route::get('locale/{locale}', function ($locale) {
    Session::put('locale', $locale);

    session()->forget('lang_dir');

    return redirect()->back();
})->name('switch_lang');

Route::group([
    'namespace' => 'Frontend',
    'middleware' => ['web', 'installed']
], function () {
    Route::get('/installer', 'InstallerController@index');
    Route::post('/installer', 'InstallerController@updateEnv')->name('ch_update_env');
    Route::get('/installer/last-step', 'InstallerController@lastStep')->name('ch_install_last_step');
    Route::post('/installer/complete', 'InstallerController@completeInstallation')->name('ch_complete_installation');
});

Route::group(['namespace' => 'Frontend', 'middleware' => ['web']], function () {
    Route::get('/page/{slug}', 'PageController@show')->name('ch_page');

    Route::post('/order/validate', 'OrderController@validateCheckoutForm')->name('ch_order_validate');
    Route::post('/order/submit', 'OrderController@submit')->name('ch_order_save');
    Route::get('/account/orders/{order_id}', 'AccountController@view_order')->name('ch_order_view');
    Route::get('attachment/{id}', 'OrderController@attachment')->name('download_attachment');

    Route::post('cart/upload', 'CartController@upload')->name('upload_attachment');
    Route::get('/gateway/token/{gateway}', 'GatewayController@getToken')->name('gateway.token');
    Route::get('/gateway/safe-redirect', 'GatewayController@safeRedirect')->name('gateway.safe.redirect');
    Route::post('/gateway/ipn/{gateway}', 'GatewayController@ipn')->name('gateway.ipn');

    // Blog Routes
    Route::get('blog', 'BlogController@index')->name('blog.index');
    Route::get('blog/category/{slug}', 'BlogController@category')->name('blog.category');
    Route::get('blog/post/{slug}', 'BlogController@post')->name('blog.post');
    Route::post('blog/post/{postId}/comment', 'BlogController@storeComment')->name('blog.post.comment.store');
    Route::put('blog/post/{postId}/comment/{commentId}', 'BlogController@updateComment')->name('blog.post.comment.update');
});

Route::group(['namespace' => 'Frontend', 'middleware' => ['web', 'check_private_mode']], function () {
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/products/all', 'ShopController@index')->name('frontend.products.all');
    Route::get('products/category/{slug?}', 'ShopController@category')->name('frontend.products.category')->where('slug', '(.*)');
    Route::get('/products/{slug}', 'ProductController@show')->name('ch_product_single');

    Route::get('/order/failed/{order_id}', 'OrderController@failed')->name('ch_order_failed');
    Route::get('/order/cancel/{order_id}', 'OrderController@cancel')->name('ch_order_cancel');
    Route::get('/order/thank-you/{order_id}', 'OrderController@completed')->name('ch_order_submitted');

    /**
     * Cart Routes
     */
    Route::get('/cart', 'CartController@show')->name('ch_cart');
    Route::get('/cart/order-summary', 'CartController@getOrderSummary')->name('ch_get_order_summary');
    Route::post('/cart/store', 'CartController@store')->name('ch_cart_save');
    Route::put('/cart', 'CartController@update')->name('ch_cart_update');
    Route::delete('/cart/remove/{rowId}', [CartController::class, 'removeItem']);
    Route::post('/cart/update', [CartController::class, 'updateCart']);

    Route::get('checkout', 'CartController@checkout')->name('ch_checkout');
    Route::post('/cart/validate-billing-info', 'CartController@validateBillingFields')->name('frontend.validate.billing-info');
    Route::get('orders/pay/{order_id}', 'CartController@payOrderShow')->name('frontend.order.pay');
    Route::post('orders/pay/{order_id}', 'OrderController@payOrderSubmit')->name('frontend.order.pay');
    Route::get('orders/pay/{order_id}/summary', 'OrderController@getOrderSummary')->name('frontend.order.summary');
});

Route::group(['namespace' => 'Frontend', 'middleware' => ['auth', 'verified']], function () {

    Route::get('/account/orders', 'AccountController@orders')->name('ch_user_orders');
    Route::get('/account/notifications', 'AccountController@notifications')->name('ch_user_notifications');

    // New Notifications Route
    Route::get('/notifications', 'NotificationsController@index')->name('notifications.index');
    Route::get('/notifications/mark-as-read/{id}', 'NotificationsController@markAsRead')->name('notifications.markAsRead');
    Route::get('/notifications/mark-all-as-read', 'NotificationsController@markAllAsRead')->name('notifications.markAllAsRead');
    Route::get('/notifications/delete-all', 'NotificationsController@deleteAll')->name('notifications.deleteAll');

    // Review Route
    Route::post('/account/orders/{orderId}', 'AccountController@postReview')->name('post.review');
    Route::get('/account/reviews', 'AccountController@reviews')->name('frontend.account.reviews');

    Route::get('/account/billing-details', 'AccountController@billingDetails')->name('ch_billing_details');
    Route::put('/account/billing-details', 'AccountController@updateBillingDetails')->name('ch_update_billing');
    Route::get('/account', 'AccountController@edit')->name('frontend.user.account');
    Route::put('/account/edit-details', 'AccountController@update')->name('ch_update_details');
    Route::get('/account/licenses', 'AccountController@licenses')->name('frontend.account.licenses');
    Route::get('/account/licenses/{id}', 'AccountController@showLicense')->name('frontend.account.licenses.show');
    Route::put('/account/licenses/{id}', 'AccountController@updateLicense')->name('frontend.account.licenses.update');

    // Downloads Routes
    Route::get('/account/downloads', 'AccountController@downloads')->name('frontend.account.downloads');
    Route::get('/account/downloads/{id}', 'AccountController@downloadVersions')->name('frontend.account.downloads.versions');
    // Deprecated direct route - keeping for fallback if needed or removal later
    Route::get('/account/download/{mediaId}', 'AccountController@downloadFile')->name('frontend.account.download_file');
    Route::get('/account/download-all/{id}', 'AccountController@downloadAll')->name('frontend.account.download_all');

    // Secure Encrypted Attachment Route
    Route::get('attachment/{id}', 'AccountController@attachment')->name('download_attachment');

    Route::get('account/tickets', [TicketsController::class, 'index'])->name('helpdesk.tickets.index');
    Route::get('account/tickets/new', [TicketsController::class, 'create'])->name('helpdesk.tickets.create');
    Route::post('account/tickets', [TicketsController::class, 'store'])->name('helpdesk.tickets.store');
    Route::get('account/tickets/{ticketId}', [TicketsController::class, 'show'])->name('helpdesk.tickets.show');
    Route::put('account/tickets/{ticketId}', [TicketsController::class, 'update'])->name('helpdesk.tickets.update');

    Route::get('/subscriptions', 'SubscriptionsController@index')->name('frontend.subscriptions.index');
    Route::get('/subscriptions/{subscription_id}', 'SubscriptionsController@show')->name('frontend.subscriptions.show');
    Route::get('/subscriptions/{subscription_id}/orders/{order_id}', 'SubscriptionsController@showSubscriptionOrder')->name('frontend.subscriptions.orders.show');
    Route::put('/subscriptions/{subscription_id}/cancel', 'SubscriptionsController@cancel')->name('frontend.subscriptions.cancel');
    Route::put('/subscriptions/{subscription_id}/reactive', 'SubscriptionsController@reactive')->name('frontend.subscriptions.reactive');

    Route::post('/upload', [TicketsController::class, 'uploadAttachment'])->name('upload_attachments');
    Route::delete('/deleteAttachment', [TicketsController::class, 'deleteAttachment'])->name('delete_attachments');
});

Route::post('ch-admin/ajax', 'Admin\AdminSettingController@ajax');

Auth::routes(['verify' => true]);
Route::get('auth/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('auth/{provider}/callback', 'Auth\LoginController@handleProviderCallback')->name('social_login_callback');

Route::group(['prefix' => 'ch-admin', 'as' => 'ch-admin.', 'namespace' => 'Admin', 'middleware' => ['auth', 'role:administrator']], function () {
    Route::get('/', 'AdminDashboardController@index')->name('ch_admin_dashboard');
    Route::get('/notifications', 'AdminDashboardController@notifications')->name('ch_admin_notifications');
    Route::get('/updates', 'AdminUpdateController@index')->name('ch_admin_update');
    Route::post('/updates', 'AdminUpdateController@update')->name('ch_update_post');
    Route::post('/updates/apply', 'AdminUpdateController@apply')->name('ch_update_apply');
    Route::get('/update/check_status', 'AdminUpdateController@update_status')->name('ch_check_status');
    Route::match(['get', 'post'], '/db-updater', 'AdminUpdateController@runMigrations')->name('db_updater');

    // New Notifications Route
    Route::get('/notifications', 'AdminNotificationsController@index')->name('notifications.index');
    Route::get('/notifications/mark-as-read', 'AdminNotificationsController@markAsRead')->name('notifications.markAsRead');
    Route::get('/notifications/mark-all-as-read', 'AdminNotificationsController@markAllAsRead')->name('notifications.markAllAsRead');
    Route::get('/notifications/delete-all', 'AdminNotificationsController@deleteAll')->name('notifications.deleteAll');

    // New Coupon Routes
    Route::get('coupons', 'AdminCouponsController@index')->name('coupons.index');
    Route::get('coupons/create', 'AdminCouponsController@create')->name('coupons.create');
    Route::post('coupons', 'AdminCouponsController@store')->name('coupons.store');
    Route::get('coupons/{id}/edit', 'AdminCouponsController@edit')->name('coupons.edit');
    Route::put('coupons/{id}', 'AdminCouponsController@update')->name('coupons.update');
    Route::delete('coupons/destroy/{id}', 'AdminCouponsController@destroy')->name('coupons.destroy');
    Route::delete('coupons/bulk-destroy', 'AdminCouponsController@bulkDestroy')->name('coupons.bulk.destroy');

    // New Category Routes
    Route::get('categories', 'AdminProductCategoriesController@index')->name('categories.index');
    Route::get('categories/create', 'AdminProductCategoriesController@create')->name('categories.create');
    Route::post('categories', 'AdminProductCategoriesController@store')->name('categories.store');
    Route::get('categories/{id}/edit', 'AdminProductCategoriesController@edit')->name('categories.edit');
    Route::put('categories/{id}', 'AdminProductCategoriesController@update')->name('categories.update');
    Route::delete('categories/destroy', 'AdminProductCategoriesController@destroy')->name('categories.destroy');

    // Product Routes (All consolidated in ProductManagerController)
    Route::get('products', 'ProductManagerController@list')->name('products.index');
    Route::get('products/create', 'ProductManagerController@index')->name('products.create');
    Route::post('products', 'ProductManagerController@store')->name('products.store');
    Route::get('products/{id}/edit', 'ProductManagerController@edit')->name('products.edit');
    Route::put('products/{id}', 'ProductManagerController@update')->name('products.update');
    Route::delete('products/destroy/{id}', 'ProductManagerController@destroy')->name('products.destroy');
    Route::delete('products/bulk-destroy', 'ProductManagerController@bulkDestroy')->name('products.bulk.destroy');
    Route::get('products/categories', 'ProductManagerController@getCategories')->name('products.categories.get');

    Route::resource('user', 'AdminUserController')->except(['destroy']);
    Route::delete('user/{user}/destroy', 'AdminUserController@destroy')
        ->name('user.destroy');
    Route::delete('user/bulk-destroy', 'AdminUserController@bulkDestroy')
        ->name('user.bulk.destroy');

    Route::resource('registration-fields', 'AdminRegistrationFieldController')->except(['show']);
    Route::post('registration-fields/reorder', 'AdminRegistrationFieldController@reorder')
        ->name('registration-fields.reorder');
//        ->middleware('can:delete,user');

    Route::post('/settings/test-email', 'AdminSettingController@sendTestEmail')->name('settings.test-email');
    Route::resource('settings', 'AdminSettingController');
    Route::resource('media', 'AdminMediaController');

    // Orders Route
    Route::resource('order', 'AdminOrderController')->except(['destroy']);
    Route::delete('order/destroy/{id}', 'AdminOrderController@destroy')->name('order.destroy');
    Route::delete('order/bulk-destroy', 'AdminOrderController@bulkDestroy')->name('order.bulk.destroy');

    Route::get('/billing-address/{userId}', 'AdminOrderController@getBillingAddress');
    Route::post('/billing-address', 'AdminOrderController@setBillingAddress')->name('setBillingInfo');
    Route::get('/plans/{productId}', 'AdminOrderController@getPlans');
    Route::get('/pricingTiers/{planId}', 'AdminOrderController@getPricingTiers');
    Route::post('/add-to-cart', 'AdminOrderController@addToCart')->name('addToCart');
    Route::post('/remove-from-cart', 'AdminOrderController@removeFromCart')->name('removeFromCart');
    Route::post('/add-addon', 'AdminOrderController@addAddon')->name('addAddon');
    Route::get('/get-cart-details', 'AdminOrderController@getCartDetails')->name('getCartDetails');
    Route::post('/apply-coupon', 'AdminOrderController@applyCoupon')->name('applyCoupon');
    Route::get('/remove-coupon', 'AdminOrderController@removeCoupon')->name('removeCoupon');
    Route::get('/states/{countryId}', 'AdminOrderController@getStates');

    Route::get('language/{lang_id}/phrases/{group?}', 'AdminLanguageController@phrases')->name('phrases.edit');
    Route::put('language/phrases/{lang_id}/{group}', 'AdminLanguageController@phrasesUpdate')->name('phrases.update');
    Route::get('language/phrases/sync', 'AdminLanguageController@sync')->name('phrases.sync');
    Route::get('language/reset-phrase-count/{lang_id?}', 'AdminLanguageController@getResetPhraseCount')->name('language.reset-phrase-count');
    Route::post('language/reset-to-default/{lang_id?}', 'AdminLanguageController@resetToDefault')->name('language.reset-to-default');
    Route::resource('language', 'AdminLanguageController');

    // Webhooks
    Route::get('webhooks', 'AdminWebhooksController@index')->name('webhooks.index');
    Route::get('webhooks/create', 'AdminWebhooksController@create')->name('webhooks.create');
    Route::post('webhooks', 'AdminWebhooksController@store')->name('webhooks.store');
    Route::get('webhooks/{id}/edit', 'AdminWebhooksController@edit')->name('webhooks.edit');
    Route::post('webhooks/{id}/update', 'AdminWebhooksController@update')->name('webhooks.update');
    Route::delete('webhooks/{id}/destroy', 'AdminWebhooksController@destroy')->name('webhooks.destroy');
    Route::delete('webhooks/bulk-destroy', 'AdminWebhooksController@bulkDestroy')->name('webhooks.bulk.destroy');

    Route::get('subscription', 'AdminSubscriptionController@index')->name('subscription.index');
    Route::get('subscription/{id}/edit', 'AdminSubscriptionController@edit')->name('subscription.edit');
    Route::put('subscription/{id}', 'AdminSubscriptionController@update')->name('subscription.update');
    Route::get('subscription/{subscription_id}/order/{order_id}/edit', 'AdminSubscriptionController@showSubscriptionOrder')->name('subscription.order.edit');
    Route::put('subscription/{subscription_id}/order/{order_id}/update', 'AdminSubscriptionController@updateSubscriptionOrder')->name('subscription.order.update');

    // Pages Routes
    Route::get('pages', 'AdminPagesController@index')->name('pages.index');
    Route::get('pages/create', 'AdminPagesController@create')->name('pages.create');
    Route::post('pages', 'AdminPagesController@store')->name('pages.store');
    Route::get('pages/{id}/edit', 'AdminPagesController@edit')->name('pages.edit');
    Route::post('pages/{id}/update', 'AdminPagesController@update')->name('pages.update');
    Route::delete('pages/{id}/destroy', 'AdminPagesController@destroy')->name('pages.destroy');
    Route::delete('pages/bulk-destroy', 'AdminPagesController@bulkDestroy')->name('pages.bulk.destroy');

    // License Routes
    Route::get('license', 'AdminLicenseController@index')->name('license.index');
    Route::get('license/create', 'AdminLicenseController@create')->name('license.create');
    Route::post('license', 'AdminLicenseController@store')->name('license.store');
    Route::get('license/{id}', 'AdminLicenseController@show')->name('license.show');
    Route::put('license/{id}', 'AdminLicenseController@update')->name('license.update');
    Route::put('license/revoke/{id}', 'AdminLicenseController@revoke')->name('license.revoke');
    Route::put('license/un-revoke/{id}', 'AdminLicenseController@unRevoke')->name('license.un.revoke');

    // FAQs - Knowledge Base Routes
    Route::get('kb/faqs', 'AdminFaqsController@index')->name('kb.faqs.index');
    Route::get('kb/faqs/create', 'AdminFaqsController@create')->name('kb.faqs.create');
    Route::post('kb/faqs', 'AdminFaqsController@store')->name('kb.faqs.store');
    Route::get('kb/product/{productId}/faqs', 'AdminFaqsController@edit')->name('kb.faqs.edit');
    Route::put('kb/product/faqs', 'AdminFaqsController@update')->name('kb.faqs.update');
    Route::delete('kb/product/{productId}/faqs', 'AdminFaqsController@destroy')->name('kb.faqs.destroy');
    Route::delete('kb/faqs/bulk-destroy', 'AdminFaqsController@bulkDestroy')->name('kb.faqs.bulk.destroy');

    // Menu Routes
    Route::get('/menus', 'AdminMenusController@index')->name('menus.index');
    Route::get('/menus/create', 'AdminMenusController@create')->name('menus.create');
    Route::post('/menus', 'AdminMenusController@store')->name('menus.store');
    Route::get('/menus/{id}/edit', 'AdminMenusController@edit')->name('menus.edit');
    Route::put('/menus/{id}', 'AdminMenusController@update')->name('menus.update');
    Route::delete('menus/{id}/destroy', 'AdminMenusController@destroy')->name('menus.destroy');
    Route::delete('menus/bulk-destroy', 'AdminMenusController@bulkDestroy')->name('menus.bulk.destroy');

    // Menu Item Routes
    Route::get('/menus/{id}/menu-item', 'AdminMenusController@builder')->name('menus.item.edit');
    Route::post('/menus/{id}/menu-item', 'AdminMenusController@builderStore')->name('menus.item.store');

    // Tickets - Tickets Routes
    Route::get('ticket', 'AdminTicketController@index')->name('ticket.index');
    Route::get('ticket/create', 'AdminTicketController@create')->name('ticket.create');
    Route::post('ticket', 'AdminTicketController@store')->name('ticket.store');
    Route::get('ticket/{id}', 'AdminTicketController@show')->name('ticket.show');
    Route::put('ticket/{id}', 'AdminTicketController@update')->name('ticket.update');
    Route::get('ticket/message/{id}/edit', 'AdminTicketController@editMessage')->name('ticket.message.edit');
    Route::post('ticket/{ticketId}/message', 'AdminTicketController@storeMessage')->name('ticket.message.store');
    Route::put('ticket/message/{id}', 'AdminTicketController@updateMessage')->name('ticket.message.update');
    Route::delete('ticket/message/{id}', 'AdminTicketController@deleteMessage')->name('ticket.message.delete');
    Route::delete('ticket/destroy', 'AdminTicketController@destroy')->name('ticket.destroy');
    Route::delete('ticket/bulk-destroy', 'AdminTicketController@bulkDestroy')->name('ticket.bulk.destroy');

    // Categories - Tickets Routes
    Route::get('ticket-category', 'AdminTicketCategoryController@index')->name('ticket.category.index');
    Route::get('ticket-category/create', 'AdminTicketCategoryController@create')->name('ticket.category.create');
    Route::post('ticket-category', 'AdminTicketCategoryController@store')->name('ticket.category.store');
    Route::get('ticket-category/{id}', 'AdminTicketCategoryController@edit')->name('ticket.category.edit');
    Route::put('ticket-category/{id}', 'AdminTicketCategoryController@update')->name('ticket.category.update');
    Route::delete('ticket-category/destroy', 'AdminTicketCategoryController@destroy')->name('ticket.category.destroy');

    // Blog Posts Routes
    Route::get('blog/posts', 'AdminBlogPostController@index')->name('blog.posts.index');
    Route::get('blog/posts/create', 'AdminBlogPostController@create')->name('blog.posts.create');
    Route::post('blog/posts', 'AdminBlogPostController@store')->name('blog.posts.store');
    Route::get('blog/posts/{id}/edit', 'AdminBlogPostController@edit')->name('blog.posts.edit');
    Route::put('blog/posts/{id}/update', 'AdminBlogPostController@update')->name('blog.posts.update');
    Route::delete('blog/posts/{id}/destroy', 'AdminBlogPostController@destroy')->name('blog.posts.destroy');
    Route::delete('blog/posts/bulk-destroy', 'AdminBlogPostController@bulkDestroy')->name('blog.posts.bulk.destroy');

    // Blog Categories Routes
    Route::get('blog/categories', 'AdminBlogCategoryController@index')->name('blog.categories.index');
    Route::get('blog/categories/create', 'AdminBlogCategoryController@create')->name('blog.categories.create');
    Route::post('blog/categories', 'AdminBlogCategoryController@store')->name('blog.categories.store');
    Route::get('blog/categories/{id}/edit', 'AdminBlogCategoryController@edit')->name('blog.categories.edit');
    Route::put('blog/categories/{id}/update', 'AdminBlogCategoryController@update')->name('blog.categories.update');
    Route::delete('blog/categories/destroy', 'AdminBlogCategoryController@destroy')->name('blog.categories.destroy');

    // Post Comments Routes
    Route::get('blog/comments', 'AdminPostCommentController@index')->name('blog.comments.index');
    Route::get('blog/comments/{id}/edit', 'AdminPostCommentController@edit')->name('blog.comments.edit');
    Route::put('blog/comments/{id}/update', 'AdminPostCommentController@update')->name('blog.comments.update');
    Route::delete('blog/comments/{id}/destroy', 'AdminPostCommentController@destroy')->name('blog.comments.destroy');
    Route::delete('blog/comments/bulk-destroy', 'AdminPostCommentController@bulkDestroy')->name('blog.comments.bulk.destroy');

    Route::get('license-error', function () {return view('admin.license.invalid_license');})->name('license.error');
});
