<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Supplier;
use App\Models\SupplierAddress;
use App\Models\SupplierNote;
use App\Models\SupplierPhone;
use App\Models\PreSettings;
use App\Models\TimeZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SupplierController extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:قائمة الموردين الحاليين', ['only' => ['index']]);
        $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);
        $suppliers = Supplier::where('company_id', $company_id)->get();
        $balances = array();
        foreach ($suppliers as $supplier) {
            $supplier_balance = $supplier->balance;
            array_push($balances, $supplier_balance);
        }
        $total_balances = array_sum($balances);
        return view('client.suppliers.index', compact('company', 'total_balances', 'company_id', 'suppliers'));
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $timezones = TimeZone::all();
        $user = Auth::user();
        $type_name = $user->company->subscription->type->type_name;
        if ($type_name == "تجربة"){
            $suppliers_count = "غير محدود";
        }
        else{
            $suppliers_count = $user->company->subscription->type->package->suppliers_count;
        }
        $company_suppliers_count = $company->suppliers->count();
        if ($suppliers_count == "غير محدود") {
            return view('client.suppliers.create',compact('company_id', 'timezones', 'company'));
        }
        else{
            if($suppliers_count > $company_suppliers_count){
                return view('client.suppliers.create',compact('company_id', 'timezones', 'company'));
            }
            else{
                return redirect()->route('client.home')->with('error','باقتك الحالية لا تسمح بالمزيد من الموردين');
            }
        }
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'supplier_name' => 'required',
            'supplier_category' => 'required',
            'balance' => 'required',
        ]);
        $data = $request->all();
        
        $company_id = $data['company_id'];
        $company = Company::FindOrFail($company_id);

        $type_name = $company->subscription->type->type_name;
        if ($type_name == "تجربة"){
            $suppliers_count = "غير محدود";
        }
        else{
            $suppliers_count = $company->subscription->type->package->suppliers_count;
        }
        $company_suppliers_count = $company->suppliers->count();
        if ($suppliers_count == "غير محدود") {
            
        }
        else{
            if(!$suppliers_count > $company_suppliers_count){

                return response()->json(['message' => 'باقتك الحالية لا تسمح بالمزيد من الموردين','status'=>false]);
            }
        }

        $balance_type = $request->balance_type;
        if ($balance_type == "for") {
            $data['balance'] =  $request->balance;
        } elseif ($balance_type == "on") {
            $data['balance'] = -1 * $request->balance;
        }
        $data['balance_start'] = $data['balance'] ;
        $supplier = Supplier::create($data);
        $notes = $request->notes;
        $phones = $request->phones;
        $addresses = $request->addresses;
        foreach ($notes as $note) {
            SupplierNote::create([
                'supplier_id' => $supplier->id,
                'supplier_note' => $note,
                'company_id' => $company_id,
            ]);
        }
        foreach ($phones as $phone) {
            SupplierPhone::create([
                'supplier_id' => $supplier->id,
                'supplier_phone' => $phone,
                'company_id' => $company_id,
            ]);
        }
        foreach ($addresses as $address) {
            SupplierAddress::create([
                'supplier_id' => $supplier->id,
                'supplier_address' => $address,
                'company_id' => $company_id,
            ]);
        }

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



    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $timezones = TimeZone::all();
        $supplier = Supplier::findOrFail($id);
        return view('client.suppliers.edit', compact('timezones', 'supplier', 'company_id', 'company'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'supplier_name' => 'required',
            'supplier_category' => 'required',
            'balance_start' => 'required',
        ]);
        $data = $request->all();
        $company_id = $data['company_id'];
        $supplier = Supplier::FindOrFail($request->id);
        $balance_type = $request->balance_type;
        if ($balance_type == "for") {
            $data['balance_start'] =  $request->balance_start;
        } elseif ($balance_type == "on") {
            $data['balance_start'] = -1 * $request->balance_start;
        }
        $supplier->update($data);
        $notes = $request->notes;
        $phones = $request->phones;
        $addresses = $request->addresses;
        $supplier->notes()->delete();
        $supplier->phones()->delete();
        $supplier->addresses()->delete();
        foreach ($notes as $note) {
            SupplierNote::create([
                'supplier_id' => $supplier->id,
                'supplier_note' => $note,
                'company_id' => $company_id,
            ]);
        }
        foreach ($phones as $phone) {
            SupplierPhone::create([
                'supplier_id' => $supplier->id,
                'supplier_phone' => $phone,
                'company_id' => $company_id,
            ]);
        }
        foreach ($addresses as $address) {
            SupplierAddress::create([
                'supplier_id' => $supplier->id,
                'supplier_address' => $address,
                'company_id' => $company_id,
            ]);
        }
        return response()->json(['message' => 'تم تعديل المورد بنجاح','status'=>true]);
    }

    public function delete(Request $request)
    {
        $supplier = Supplier::FindOrFail($request->id);
        if ($supplier->balance != '0') {
            return response()->json(['message' => 'خطأ في حذف المورد', 'sol'=>'يرجي تسوية ديون المورد أولا','status'=>false]);
        } else {
            $supplier->phones()->delete();
            $supplier->notes()->delete();
            $supplier->addresses()->delete();
            $supplier->delete();
            return response()->json(['message' => 'تم حذف المورد بنجاح','status'=>true]);
        }
    }

    public function print()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $suppliers = Supplier::where('company_id', $company_id)->get();
        return view('client.suppliers.print', compact('suppliers', 'company'));
    }


}
