<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Color;
use App\Models\Company;
use App\Models\PreSettings;
use App\Models\Product;
use App\Models\Product_unit;
use App\Models\Size;
use App\Models\Store;
use App\Models\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class ProductController extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:قائمة المنتجات')->only(['index','empty']);
        $this->middleware('permission:اضافة منتج جديد')->only(['create','store']);
        $this->middleware('permission:تعديل منتج')->only(['edit','update']);
        $this->middleware('permission:حذف منتج')->only('delete');
        

    }
    public function index()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = Product::product()->where('company_id',$company_id)
            // ->where('balance','>',0)
            ->get();
        $purchase_prices = array();
        $balances = array();
        foreach($products as $product){
            $product_price = $product->purchasing_price;
            $product_balance = $product->balance;
            array_push($balances,$product_balance);

            $total_price = $product_price * $product_balance;
            array_push($purchase_prices,$total_price);
        }
        $total_purchase_prices = array_sum($purchase_prices);
        $total_balances = array_sum($balances);
        return view('client.products.index', compact('company','total_balances','total_purchase_prices', 'company_id', 'products'));
    }


    public function empty()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = Product::product()->where('company_id',$company_id)
            ->where('balance','=',0)
            ->get();
        return view('client.products.empty', compact('company', 'company_id', 'products'));
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $stores = Store::where('company_id',$company_id)->get();
        $categories = Category::where('company_id',$company_id)->get();
        $sizes = Size::where('company_id',$company_id)->get();
        $colors = Color::where('company_id',$company_id)->get();
        $units = $company->units;
        return view('client.products.create',
            compact('company_id','units','sizes','colors','categories','stores', 'company'));
    }

    public function store(Request $request)
    {
        if(!$request->is_product){

            $request['balance'] ="0" ;
            $request['unit_id'] = Unit::where('company_id',$request->company_id)->where('unit_name','وحدة')->first()->id ;
            $request['store_id'] ="0" ;

        }

        $this->validate($request, [
            'store_id' => 'required',
            'category_id' => 'required',
            'product_name' => 'required',
            'unit_id' => 'required',
            'balance' => 'required',
            'wholesale_price' => 'required|numeric',
            'sector_price' => 'required|numeric',
            'purchasing_price' => 'required|numeric',
        ]);
        $data = array_merge($request->all(),['balance_start'=>$request->balance]);
        $company_id = $data['company_id'];
        $product = Product::create($data);
        $product->sizes()->syncWithoutDetaching($request->sizes);
        $product->colors()->syncWithoutDetaching($request->colors);

        // if($product->is_product == 1) {
        $this->set_product_unit($product->id);
        // }
        
        if ($request->hasFile('product_pic')) {
            $image = $request->file('product_pic');
            $fileName = $image->getClientOriginalName();
            $uploadDir = 'uploads/products/' . $product->id;
            $image->move($uploadDir, $fileName);
            $product->product_pic = $uploadDir . '/' . $fileName;
            $product->save();
        }
        return response()->json(['message' => 'تم إضافة المنتج بنجاح','status'=>true]);
    }
    public function show($id){
        $product = Product::FindOrFail($id);
        return view('client.products.show', compact('product'));
    }

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $stores = Store::where('company_id',$company_id)->get();
        $categories = Category::where('company_id',$company_id)->get();
        $product = Product::findOrFail($id);
        $units = $company->units;
        $all_colors = Color::where('company_id',$company_id)->get();
        $colors = array();
        foreach ($product->colors as $color) {
            array_push($colors,$color->id);
        }
        $all_sizes = Size::where('company_id',$company_id)->get();
        $sizes = array();
        foreach ($product->sizes as $size) {
            array_push($sizes,$size->id);
        }

        $product_units = $product->product_units;

        return view('client.products.edit', compact('stores','units','categories','all_sizes','sizes','all_colors','colors','product','product_units','company_id', 'company'));
    }

    public function update(Request $request)
    {

        if(!$request->is_product){

            $request['balance'] ="0" ;
            $request['unit_id'] = Unit::where('company_id',$request->company_id)->where('unit_name','وحدة')->first()->id ;
            $request['store_id'] ="0" ;

        }


        $this->validate($request, [
            'store_id' => 'required',
            'category_id' => 'required',
            'product_name' => 'required',
            'unit_id' => 'required',
            'balance_start' => 'required',
            'wholesale_price' => 'required|numeric',
            'sector_price' => 'required|numeric',
            'purchasing_price' => 'required|numeric',
        ]);

        $data = $request->all();
        $company_id = $data['company_id'];
        $product = Product::findOrFail($request->id);
        $product->update($data);
        $product->sizes()->sync($request->sizes);
        $product->colors()->sync($request->colors);

        if ($request->hasFile('product_pic')) {
            $image = $request->file('product_pic');
            $fileName = $image->getClientOriginalName();
            $uploadDir = 'uploads/products/' . $product->id;
            $image->move($uploadDir, $fileName);
            $product->product_pic = $uploadDir . '/' . $fileName;
            $product->save();
        }
        
        return response()->json(['message' => 'تم تحديث المنتج بنجاح','status'=>true]);
        }

    public function delete(Request $request)
    {
        $product = Product::FindOrFail($request->id);
        $product->delete();
        return response()->json(['message' => 'تم حذف المنتج بنجاح','status'=>true]);
    }
    public function print(){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = Product::product()->where('company_id',$company_id)
            ->where('balance','>',0)
            ->get();
        return view('client.products.print', compact('products','company'));
    }
    public function limited()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = Product::product()->where('company_id',$company_id)
            ->where('balance','>','0')
            ->whereColumn('balance', '<', 'min_balance')
            ->get();
        return view('client.products.limited', compact('company', 'company_id', 'products'));
    }


    public function services(){

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $services = Product::service()->where('company_id',$company_id)->get();
        return view('client.products.services', compact('company', 'company_id', 'services'));

    }

    public function units_update(Request $request){
        $company_id = Auth::user()->company_id;
        $product = Product::FindOrFail($request->product_id);
        $product->product_units()->delete();
        $data = $request->all();
        for($i=0;$i<count($data['secondary_unit_id']);$i++){
            Product_unit::create([
                'company_id'=>$company_id,
                'product_id'=>$data['product_id'],
                'product_primary_unit_id'=>$product->unit_id,
                'secondary_unit_id'=>$data['secondary_unit_id'][$i],
                'quantity'=>$data['quantity'][$i],
                'price'=>$data['price'][$i],
                'barcode'=>$data['barcode'][$i],
                'user_id'=> Auth::user()->id,
            ]);
        }
        return response()->json(['message' => 'تم تحديث الوحدات بنجاح','status'=>true]);
    }

    public function set_product_unit($product){

        $product = Product::FindOrFail($product);
        $units = Unit::where('company_id',$product->company_id)->get();
        foreach ($units as $unit){
              $product_unit =  Product_unit::create([
                    'company_id'=>$product->company_id,
                    'product_id'=>$product->id,
                    'product_primary_unit_id'=>$product->unit_id,
                    'secondary_unit_id'=>$unit->id,
                    'quantity'=>1,
                    'user_id'=> Auth::user()->id,
                ]);

                if($unit->id == $product->unit_id){
                    $product_unit->update([
                        'price'=>$product->sector_price,
                    ]);
                }
            
        }

    }
}
