<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Unit;
use App\Models\Company;
use App\Models\Product;
use App\Models\Product_unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class UnitController extends Controller
{
    public function index(){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $units = $company->units;
        return view('client.units.index',compact('company','company_id','units'));
    }
    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        return view('client.units.create',compact('company_id','company'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'unit_name' => 'required',
        ]);
        $data = $request->all();
        $data['primary_unit'] = 0;
        $unit = Unit::create($data);
        $this->setUnitForProducts($unit);
        return response()->json([
            'message' => 'تم اضافة الوحدة بنجاح',
            'status' => true
        ]);
            
    }

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $unit = Unit::findOrFail($id);
        return view('client.units.edit', compact('unit', 'company_id', 'company'));
    }
    public function update(Request $request)
    {
        $this->validate($request, [
            'unit_name' => 'required',
        ]);
        $input = $request->all();
        $unit = Unit::findOrFail($request->id);
        $unit->update($input);
        return response()->json([
            'message' => 'تم تعديل الوحدة بنجاح',
            'status' => true
        ]);
    }
    public function delete(Request $request)
    {
        $unit = Unit::findOrFail($request->id);
        if($unit->primary_unit == 0){
        
            $unit->delete();

        return response()->json([
            'message' => 'تم حذف الوحدة بنجاح',
            'status' => true
        ]);

        }else{
           
            return response()->json([
                'message' => 'لا يمكن حذف الوحدة الاساسية',
                'status' => false
            ]);
    
        }

    }

    public function setUnitForProducts($unit){
        $company_id = Auth::user()->company_id;
        $products = Product::product()->where('company_id',$company_id)->get();
        foreach($products as $product){
            Product_unit::create([
                'company_id'=>$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,
            ]);
        }
    }
}
