<?php

namespace App\Http\Controllers;

use App\Models\ad;
use App\Models\maincategories;
use App\Models\mainproducts;
use App\Models\productview;
use App\Models\normaluser;
use App\Models\mainbanners;
use App\Models\order;
use App\Models\country;
use App\Models\vendorsSubscriptions;
use App\Models\vendor;
use App\Models\subscription;
use App\Models\admin;
use App\Models\ui_Categories;
use App\Models\dashboardNotification;
use App\Models\ui_products;
use App\Models\ui_header;
use App\Models\ui_footer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Blade;

class HomeController extends Controller
{
    // Website ==============================================================================================================

    public function homeLocale(Request $request)
    {
        $websiteName = $request->segment(2);
        $lang = "ar";
        $langen = "en";

        $currentURL = url()->current();
        $url = ("vendor/{$websiteName}/{$lang}");
        $urlen = ("vendor/{$websiteName}/{$langen}");
        if (Str::contains($currentURL, 'en')) {
            return redirect($urlen);
        } else {
            return redirect($url);
        }
    }
    public function Home(Request $request)
    {

        $ads = ad::where(['ad_vendor_id' => Session::get('website_id')])->with('country', 'governate')->get();
        $categories = maincategories::with('banners')->where(['mainCategoryIsActivated' => "1", 'mainCategory_vendor_id' => Session::get('website_id')])->get();
        $products = productview::with('country')->where(['mainProduct_vendor_id' => Session::get('website_id')])->with('category')->paginate(20);
        $mainbanners = mainbanners::where(['mainbanner_state' => 1, 'mainbanner_vendor_id' => Session::get('website_id')])->get();
        $countries = country::where(['country_state' => 1])->get();


        // ui_header
        $ui_header = ui_header::with('ui')->where(['ui_headers_id' => Session::get('settings_Header_id'), 'ui_headers_vendor_id' => Session::get('website_id'),])->get();
        // Compile and render the Blade content
        $compiled_ui_header = Blade::compileString($ui_header[0]->ui['ui_content']);
        // ui_header

        // ui_Category
        $ui_Category = ui_Categories::with('ui')->where(['ui_categories_id' => Session::get('settings_category_id'), 'ui_categories_vendor_id' => Session::get('website_id'),])->get();
        // Compile and render the Blade content
        $compiled_ui_Category = Blade::compileString($ui_Category[0]->ui['ui_content']);
        // ui_Category

        // ui_products
        $ui_products = ui_products::where(['ui_products_id' => Session::get('settings_Products_id'), 'ui_products_vendor_id' => Session::get('website_id'),])->get();
        // Compile and render the Blade content
        $compiled_ui_products = Blade::compileString($ui_products[0]->ui['ui_content']);
        // ui_products

        // ui_footer
        $ui_footer = ui_footer::with('ui')->where(['ui_footers_id' => Session::get('settings_Footer_id'), 'ui_footers_vendor_id' => Session::get('website_id'),])->get();
        // Compile and render the Blade content
        $compiled_ui_footer = Blade::compileString($ui_footer[0]->ui['ui_content']);
        // ui_footer


        return view(
            'home',
            [
                'mainbanners' => $mainbanners,
                'products' => $products,
                'categories' => $categories,
                'ads' => $ads,
                'countries' => $countries,
                'compiled_ui_Category' => $compiled_ui_Category,
                'compiled_ui_products' => $compiled_ui_products,
                'compiled_ui_header' => $compiled_ui_header,
                'compiled_ui_footer' => $compiled_ui_footer,
            ]
        );
    }
    public function country(Request $request)
    {
        $currency = $request->segment(6);
        $exchangeRates = config('currencies.currencies');

        if (isset($exchangeRates[$currency])) {
            Session::put('currency', $currency);
        } else {
            Session::put('currency', 'EGP');
        }

        return redirect()->back();
    }
    public function config(Request $request)
    {
        $normalUser_id = Session::get('userID');
        $websiteID = Session::get('website_id');
        $addressData  =  DB::select("SELECT * FROM normaluseraddress
        INNER JOIN normalusers ON normalusers.normalUser_id = $normalUser_id
        AND normaluseraddress.normaluserAddress_userid = $normalUser_id
        INNER JOIN selected_shipping_cities ON selected_shipping_cities.selected_shipping_city_id = normaluseraddress.normaluserAddress_cityID
        WHERE normaluserAddress_vendor_id = $websiteID");

        // User
        $user = normaluser::where(['normalUser_id' => $normalUser_id, 'normalUser_vendor_id' => $websiteID])->get();
        $orders = order::with('user', 'address', 'orderStatus', 'country')->where(['order_vendor_id' => Session::get('website_id'), 'order_userid' => Session::get('userID')])->paginate(10);
        return view('config.config')->with(['orders' => $orders, 'addressData' => $addressData, 'user' => $user]);
    }
    public function showOrderTracking(Request $request)
    {
        $id = $request->id;
        $order = order::with('user', 'address', 'orderStatus', 'country')->where(['order_vendor_id' => Session::get('website_id'), 'order_userid' => Session::get('userID'), 'order_id' => $id])->paginate(10);
        return view('config.showOrderTracking')->with(['order' => $order]);
    }


    // Website ==============================================================================================================

    // Dashboard ========================================================================================================================
    public function homeDashboard(Request $request)
    {
        $categories = maincategories::count();
        $mainproducts = mainproducts::count();
        $normaluser = normaluser::where(['normalUser_type' => "1"])->count();

        // Today Sales
        $todaySales = order::where(['order_vendor_id' => Session::get('vendor_id')])->get('order_price')->sum('order_price');
        // Today Sales

        $sales = order::select(DB::raw('SUM(order_price) as total_sales'), DB::raw('MONTH(created_at) as month'))
            ->groupBy(DB::raw('MONTH(created_at)'))
            ->get();

        $vendorid = Session::get('vendor_id');
        $vendor = vendor::where(['vendor_id' => $vendorid])->get();
        $vendors = vendor::where(['vendor_websiteuser_id' => Session::get('website_user_id')])->get();
        $vendorsSubscriptions = vendorsSubscriptions::where(['vendors_subscriptions_vendor_id' => $vendorid])->with(['vendor', 'subscription'])->get();
        $subscriptions = subscription::where(['subscription_State' => "1"])->where('subscription_Price', '!=', '0')->get();

        $products = mainproducts::where(['mainProduct_vendor_id' => $vendorid])->count();
        $categories = maincategories::where(['mainCategory_vendor_id' => $vendorid])->count();
        $admins = admin::where(['admin_vendor_id' => $vendorid])->count();
        $orders = order::where(['order_vendor_id' => $vendorid])->count();

        $courses = order::selectRaw('COUNT(*) as count, MONTH(created_at) as month')
            ->groupBy('month')->where(['order_vendor_id' => $vendorid])
            ->get();

        $totalSales = order::sum('order_price');
        $startDateNow = Carbon::now();

        if ($vendorsSubscriptions->isEmpty()) {
            return view('dashboard.home')->with([
                'categories' => $categories,
                'mainproducts' => $mainproducts,
                'normaluser' => $normaluser,
                'todaySales' => $todaySales,
                'sales' => $sales,
                'vendor' => $vendor,
                'vendors' => $vendors,
                'subscriptions' => $subscriptions,
                'products' => $products,
                'admins' => $admins,
                'orders' => $orders,
                'courses' => $courses,
                'totalSales' => $totalSales,

                'vendorsSubscriptions' => $vendorsSubscriptions,
            ]);
        } else {
            $startDate = Carbon::create($vendorsSubscriptions[0]->vendors_subscriptions_DateToBegin);

            $endDate = Carbon::create($vendorsSubscriptions[0]->vendors_subscriptions_DateToEnd); // or Carbon::parse('2023-01-15');

            $daysAvailable = $startDate->diffInDays($endDate);
            $days = $startDateNow->diffInDays($endDate);
        }
        return view('dashboard.home')->with([
            'categories' => $categories,
            'mainproducts' => $mainproducts,
            'normaluser' => $normaluser,
            'todaySales' => $todaySales,
            'sales' => $sales,
            'vendor' => $vendor,
            'vendors' => $vendors,
            'subscriptions' => $subscriptions,
            'products' => $products,
            'admins' => $admins,
            'orders' => $orders,
            'courses' => $courses,
            'totalSales' => $totalSales,
            'days' => $days,
            'daysAvailable' => $daysAvailable,
            'vendorsSubscriptions' => $vendorsSubscriptions,
        ]);
    }
    public function dashboardNotifications(Request $request)
    {
        $results = dashboardNotification::where('dashboard_notifications_vendorid', Session::get('vendor_id'))->orderBy('created_at', 'desc')->paginate(6); // Adjust the column and model as needed

        $formattedResults = $results->map(function ($item) {
            return [
                'order_id' => $item->order_id, // Adjust the field for the image URL
                'title' => $item->dashboard_notifications_title, // Adjust the field you want to return
                'body' => $item->dashboard_notifications_body, // Adjust the field for the image URL
                'created_at' => $item->created_at->format('d M Y H:i'), // Replace with your actual route name and parameters
                'seen' => $item->dashboard_notifications_seen, // Replace with your actual route name and parameters
            ];
        });

        return response()->json($formattedResults);
    }
    public function dashboardOnboarding(Request $request)
    {
        // Validate the request (optional)
        $request->validate([
            'action' => 'required|string',
        ]);

        // Get the action from the request
        $action = $request->input('action');

        // Perform logic based on the action
        if ($action === 'ok') {
            $message = 'User clicked OK';
        } elseif ($action === 'dont_show_again') {
            
            $query = admin::where([
                'admin_id' => Session::get('id'),
                'admin_vendor_id' => Session::get('vendor_id'),
            ])->update([
                'admin_onboarding' => 1
            ]);
            if ($query) {
                $message = 'User clicked Don\'t show again';
            }
        } else {
            $message = 'Unknown action';
        }

        // Return a JSON response
        return response()->json([
            'message' => $message,
        ]);
    }

    // Dashboard ========================================================================================================================



    // Administration =======================================================================================
    public function AdministrationHome()
    {
        return view('administration.home');
    }
    // Administration =======================================================================================

}
