<?php

namespace Yas\FrontTheme\Http\Controllers\Customer\Account;

use Webkul\Checkout\Facades\Cart;
use Webkul\Core\Traits\PDFHandler;
use Webkul\Sales\Repositories\InvoiceRepository;
use Webkul\Sales\Repositories\OrderRepository;
use Yas\FrontTheme\DataGrids\OrderDataGrid;
use Yas\FrontTheme\Http\Controllers\Controller;
use Yas\Product\Repositories\ProductRepository;
use Webkul\Theme\Repositories\ThemeCustomizationRepository;
use Yas\Company\Repositories\CompanyRepository;
use Webkul\Category\Repositories\CategoryRepository;

class OrderController extends Controller
{
    use PDFHandler;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(
        protected OrderRepository $orderRepository,
        protected InvoiceRepository $invoiceRepository,
        protected ProductRepository $productRepository,
        protected ThemeCustomizationRepository $themeCustomizationRepository,
        protected CompanyRepository $companyRepository,
        protected CategoryRepository $categoryRepository,
    ) {}

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        if (request()->ajax()) {
            return datagrid(OrderDataGrid::class)->process();
        }

        return view('yas_theme::customers.account.orders.index');
    }

    /**
     * Show the view for the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function view($id)
    {
        $order = $this->orderRepository->findOneWhere([
            'customer_id' => auth()->guard('customer')->id(),
            'id'          => $id,
        ]);

        abort_if(! $order, 404);

        return view('yas_theme::customers.account.orders.view', compact('order'));
    }

    /**
     * Reorder action for the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function reorder(int $id)
    {
        $order = $this->orderRepository->findOrFail($id);

        foreach ($order->items as $item) {
            try {
                Cart::addProduct($item->product, $item->additional);
            } catch (\Exception $e) {
                // do nothing
            }
        }

        return redirect()->route('yas_theme.checkout.cart.index');
    }

    /**
     * Print and download the for the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function printInvoice($id)
    {
        $invoice = $this->invoiceRepository->where('id', $id)
            ->whereHas('order', function ($query) {
                $query->where('customer_id', auth()->guard('customer')->id());
            })
            ->firstOrFail();

            $company = $this->companyRepository->find($invoice->order->company_id);
            if(!$company){
                $company = null;
            }
    
            $invoiceText = $this->themeCustomizationRepository->findWhere([
                'name'=>'Invoice content'
            ]);

            $productAttributesForInvoice  = [];
            $productShortDescription  = [];
            foreach($invoice->items as $item){
                $product = $this->productRepository->with('categories')->find($item->product_id);
            
                if($product->categories()->first()){
                    $selectedCategoryId = $product->categories()->first()->id;
                }else{
                    $selectedCategoryId = null;
                }

                $categoryName = "";
                if($selectedCategoryId){
                    $category = $this->categoryRepository->findOrFail($selectedCategoryId);
                    $categoryName = $category->name;
                }

                $productShortDescription[$product->sku] = $product->short_description; 
                
                foreach ($product->attribute_family->attribute_groups->groupBy('column') as $column => $groups){
                    foreach ($groups as $group){
                        if($group->code == 'custom'){
                            $customAttributes = $product->getEditableAttributes($group);
                            if (count($customAttributes)){
                                foreach ($customAttributes as $attribute){
                                    // if($attribute->type == 'select'){
                                    //     $attributeName = $attribute->admin_name;
                                    //     $options = $attribute->options()->orderBy('sort_order')->get();
                                    //     foreach ($options as $option){
                                    //         if($attribute->code == 'condition'){
                                    //             if($option->id == $product->condition){
                                    //                 $productAttributesForInvoice[$product->sku][$attribute->code] = $option->admin_name; 
                                    //             }
                                    //         }
                                    //         if($attribute->code == 'hardware'){
                                    //             if($option->id == $product->hardware){
                                    //             $productAttributesForInvoice[$product->sku][$attribute->code] = $option->admin_name;
                                    //             }
                                    //         }
                                            
                                    //     }
                                    // }
        
                                    
                                    // if($attribute->code = 'color'){
                                    //     $productAttributesForInvoice[$product->sku][$attribute->code] = $product->color;
                                    // }
                                    // if($attribute->code = 'material'){
                                    //     $productAttributesForInvoice[$product->sku][$attribute->code] = $product->material;
                                    // }
                                    if($product->{$attribute->code}){
                                        if($attribute->type == 'boolean'){
                                            $productAttributesForInvoice[$product->sku][$attribute->code] = $attribute->admin_name;
                                        }
                                        
                                    }
                                }
                                
                            }
                        }
                    }
                }
            }

        return $this->downloadPDF(
            view('yas_theme::customers.account.orders.pdf', compact('invoice','productAttributesForInvoice','productShortDescription','company','categoryName','invoiceText'))->render(),
            'invoice-'.$invoice->created_at->format('d-m-Y')
        );
    }

    /**
     * Cancel action for the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function cancel($id)
    {
        $customer = auth()->guard('customer')->user();

        /* find by order id in customer's order */
        $order = $customer->orders()->find($id);

        /* if order id not found then process should be aborted with 404 page */
        if (! $order) {
            abort(404);
        }

        $result = $this->orderRepository->cancel($order);

        if ($result) {
            session()->flash('success', trans('yas_theme::app.customers.account.orders.view.cancel-success', ['name' => trans('admin::app.customers.account.orders.order')]));
        } else {
            session()->flash('error', trans('yas_theme::app.customers.account.orders.view.cancel-error', ['name' => trans('admin::app.customers.account.orders.order')]));
        }

        return redirect()->back();
    }
}
