<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Mail\sendingBuyBill;
use App\Models\Bank;
use App\Models\BankBuyCash;
use App\Models\BankCash;
use App\Models\BuyBillReturn;
use App\Models\BuyCash;
use App\Models\Cash;
use App\Models\Company;
use App\Models\ExtraSettings;
use App\Models\Supplier;
use App\Models\PreSettings;
use App\Models\Product;
use App\Models\Safe;
use App\Models\BuyBill;
use App\Models\BuyBillElement;
use App\Models\BuyBillExtra;
use App\Models\Client;
use App\Models\Product_unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class BuyBillController 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);
        $buy_bills = BuyBill::active()->where('company_id', $company_id)->get();
        $suppliers = $company->suppliers;
        $products = $company->products;
        $clients = $company->clients;

    
        return view('client.buy_bills.index', compact('company', 'products', 'company_id', 'suppliers', 'buy_bills','clients'));
    }



    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $categories = $company->categories;
        $all_products = $company->products;
        $stores = $company->stores;
        $units = $company->units;
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $pre_settings = PreSettings::where('company_id', $company_id)->first();

        $suppliers = Supplier::where('company_id', $company_id)->get();
        $check = BuyBill::where('company_id', $company_id)->get();
        if ($check->isEmpty()) {
            $pre_bill = $pre_settings->pre_buy_bill;
        } else {
            $old_pre_bill = BuyBill::where('company_id',$company->id)->latest()->value('buy_bill_number');
            $pre_bill = ++$old_pre_bill;
        }
        $check = BuyCash::where('company_id', $company->id)->get();
        if ($check->isEmpty()) {
            $pre_cash = $pre_settings->pre_buy_cash;
        } else {
            $old_cash = BuyCash::where('company_id',$company->id)->max('cash_number');
            $pre_cash = ++$old_cash;
        }

        $safes = $company->safes;
        $banks = $company->banks;
        $user = Auth::user();

        $bills_count = $user->company->subscription->package->bills_count;
        $company_bills_count = $company->buy_bills->count();

        if ($bills_count == "غير محدود" || $bills_count > $company_bills_count) { $allowToBill = true;}else{$allowToBill = false;}

        if ($allowToBill) {
            
            $step = BuyBill::with(['elements'=>function($q){$q->with('elements_unit');}])->where('company_id', $company_id)
            ->where('client_id', $client_id)
            ->where('status', 'open')
            ->first();

        if (!empty($step)) {
            $open_buy_bill = $step;
            $buy_bill_cash = BuyCash::where('company_id', $company_id)->where('bill_id', $open_buy_bill->buy_bill_number)->first();
            $buy_bill_bank_cash = BankBuyCash::with('bank')->where('company_id', $company_id)->where('company_id', $company_id)->where('bill_id', $open_buy_bill->buy_bill_number)->first();
        } else {
            $open_buy_bill = null;
            $buy_bill_cash = null;
            $buy_bill_bank_cash = null;
        }

        return view('client.buy_bills.create',
                compact('company', 'open_buy_bill', 'units', 'pre_cash', 'stores', 'safes', 'banks', 'suppliers', 'categories', 'extra_settings'
                    , 'company_id', 'all_products', 'pre_bill', 'buy_bill_cash', 'buy_bill_bank_cash'));

        
        }else {
           
                return redirect()->route('client.home')->with('error', 'باقتك الحالية لا تسمح بالمزيد من فواتير الشراء');
        }
        
    }
//
    public function store_cash_suppliers(Request $request)
    {
        $this->validate($request, [
            'cash_number' => 'required',
            'supplier_id' => 'required',
            'amount' => 'required',
            'date' => 'required',
            'time' => 'required',
        ]);

        $data = $request->all();
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $supplier_id = $data['supplier_id'];
        $amount = $data['amount'];
        $supplier = Supplier::FindOrFail($supplier_id);
        $balance_before = $supplier->balance;
        $balance_after = $balance_before - $amount;
        $data['balance_before'] = $balance_before;
        $data['balance_after'] = $balance_after;
        $payment_method = $data['payment_method'];
        $buy_bill = BuyBill::where('company_id', $company_id)->where('buy_bill_number',$request->bill_id)->first();
        $cash = BuyCash::where('bill_id', $request->bill_id)->where('company_id', $company_id)->first();
        $bank_cash = BankBuyCash::where('bill_id', $request->bill_id)->where('company_id', $company_id)->first();


        if ($payment_method == "cash") {
            if (empty($cash)) {
                $cash = BuyCash::create($data);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => 'غير مسموح لك .. تم الدفع من قبل'
                ]);
            }
        } else {
            if (empty($bank_cash)) {
                $bank_cash = BankBuyCash::create($data);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => 'غير مسموح لك .. تم الدفع من قبل'
                ]);
            }
        }
        if ($cash || $bank_cash) {
            $safe = "";
            $bank = "";
            if ($payment_method == "cash") {
                $pay_method = 'دفع نقدى كاش ';
                $safe = $cash->safe->safe_name;
                $cash_id = $cash->id;
                $amount = $cash->amount;


            } elseif ($payment_method == "bank") {
                $pay_method = 'دفع بنكى شبكة ';
                $bank = $bank_cash->bank->bank_name;
                $cash_id = $bank_cash->id;
                $amount = $bank_cash->amount;

            }

            if(!empty($bank_cash) || !empty($cash)){

                if(!empty($bank_cash)&&!empty($cash)){
                    $paid = $cash->amount+$bank_cash->amount;
                }elseif(!empty($cash)){
                    $paid = $cash->amount;
                }elseif(!empty($bank_cash)){
                    $paid = $bank_cash->amount;
                }
            }
            if($buy_bill->status == "open"){

                $rest = $buy_bill->final_total - $paid;
                $buy_bill->update([
                    'paid' => $paid,
                    'rest' => $rest,
                ]);
            }else{

                $buy_bill->update([
                    'paid' => $paid,
                ]);

            }

            return response()->json([
                'status' => true,
                'message' => 'تم تسجيل الدفع بنجاح' ,
                'cash_number' => $cash_id,
                'amount' => $amount,
                'safe' => $safe,
                'bank' => $bank,
                'method' => $payment_method,

            ]);

        } else {
            return response()->json([
                'status' => false,
                'message' => 'هناك خطأ فى تسجيل الدفع النقدى حاول مرة اخرى',
            ]);
        }
    }

    public function pay_delete(Request $request)
    {
        $payment_method = $request->payment_method;
        $cash_id = $request->cash_id;
        if ($payment_method == "cash") {
            $cash = BuyCash::FindOrFail($cash_id);
            if($cash->buybill->status == 'done'){

                $amount = $cash->amount;
                $safe_id = $cash->safe_id;
                $safe = Safe::FindOrFail($safe_id);
                $safe_balance_before = $safe->balance;
                $safe_balance_after = $safe_balance_before + $amount;
                $safe->update([
                    'balance' => $safe_balance_after
                ]);

            }
                $cash->buybill->update([
                    'paid' => $cash->buybill->paid - $cash->amount,
                ]);

                if($cash->buybill->status == 'open'){
                    $cash->buybill->update([
                        'rest' => $cash->buybill->final_total - $cash->buybill->paid,
                    ]);
                }
            

            $cash->delete();
            

        } elseif ($payment_method == "bank") {
            $bank_cash = BankBuyCash::FindOrFail($cash_id);
            if($bank_cash->buybill->status == 'done'){
            $amount = $bank_cash->amount;
            $bank_id = $bank_cash->bank_id;
            $bank = Bank::FindOrFail($bank_id);
            $bank_balance_before = $bank->bank_balance;
            $bank_balance_after = $bank_balance_before + $amount;
            $bank->update([
                'bank_balance' => $bank_balance_after
            ]);

            }
               
                $bank_cash->buybill->update([
                    'paid' => $bank_cash->buybill->paid - $bank_cash->amount,
                ]);

                if($bank_cash->buybill->status == 'open'){
                    $bank_cash->buybill->update([
                        'rest' => $bank_cash->buybill->final_total - $bank_cash->buybill->paid,
                    ]);
                }

            $bank_cash->delete();

        }
        

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

    public function save(Request $request)
    {
        $data = $request->all();
        $data['company_id'] = Auth::user()->company_id;
        $company = Company::FindOrFail($data['company_id']);
        $data['client_id'] = Auth::user()->id;
        $data['status'] = 'open';
        $product_unit = Product_unit::where('product_id', $request->product_id)->where('secondary_unit_id', $request->unit_id)->first();
        $BuyBill = BuyBill::where('company_id',$data['company_id'])->where('buy_bill_number', $data['buy_bill_number'])->first();
        if (empty($BuyBill)) {
            $BuyBill = BuyBill::create($data);
        } else {
            $BuyBill->update($data);
        }
        $data['buy_bill_id'] = $BuyBill->id;
        $data['company_id'] = $company->id;

        $check = BuyBillElement::where('company_id',$data['company_id'])->where('buy_bill_id', $BuyBill->id)
            ->where('product_id', $request->product_id)
            ->where('unit_id', $request->unit_id)
            ->where('company_id', $company->id)
            ->first();
        if (empty($check)) {
            $buy_bill_element = BuyBillElement::create($data);
        } else {
            $old_quantity = $check->quantity;
            $new_quantity = $old_quantity + $request->quantity;
            $product_price = $request->product_price;
            $new_quantity_price = $new_quantity * $product_price ;
            $unit_id = $request->unit_id;
            $buy_bill_element = $check->update([
                'product_price' => $product_price,
                'quantity' => $new_quantity,
                'unit_id' => $unit_id,
                'quantity_price' => $new_quantity_price,
            ]);
        }

        if ($BuyBill && $buy_bill_element) {
            $all_elements = BuyBillElement::where('company_id',$data['company_id'])->where('buy_bill_id', $BuyBill->id)->get();
            return response()->json([
                'status' => true,
                'msg' => 'تمت الاضافة الى الفاتورة بنجاح',
                'all_elements' => $all_elements,
                'unit_quantity' => $product_unit->quantity,
            ]);
        } else {
            $all_elements = BuyBillElement::where('company_id',$data['company_id'])->where('buy_bill_id', $BuyBill->id)->get();
            return response()->json([
                'status' => false,
                'msg' => 'هناك خطأ فى عملية الاضافة',
                'all_elements' => $all_elements,
            ]);
        }
    }

    public function saveAll(Request $request){

        $data = $request->all();
        $after_total_all = $request->total;
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $buy_bill = BuyBill::where('company_id',$company_id)->where('buy_bill_number', $request->buy_bill_number)->first();
        
        if($request->status=='done'){
             $this->editBuyBill($buy_bill->id,$request);
        }

        $buy_bill->update([
            'state' => 'done',
            'final_total'=> $after_total_all,
        ]);

        $this->check_bill_paid($buy_bill);

        $buyBillElement = $buy_bill->elements;

        foreach ($buyBillElement as $element) {
            $product = Product::FindOrFail($element->product_id);
            $unit_prodroduct = Product_unit::where('product_id',$product->id)->where('secondary_unit_id',$element->unit_id)->first();
            $old_product_balance = $product->balance;
            $new_product_balance = $old_product_balance + $element->quantity*$unit_prodroduct->quantity ;
            $product->update([
                'balance' => $new_product_balance
            ]);
        }

            
    }


    public function check_bill_paid($buy_bill){

        $company_id = Auth::user()->company_id;
        $final_total = $buy_bill->final_total;

        $cash = BuyCash::where('bill_id', $buy_bill->buy_bill_number)
        ->where('company_id', $company_id)
        ->first();

        $bank_cash = BankBuyCash::where('bill_id', $buy_bill->buy_bill_number)
        ->where('company_id', $company_id)
        ->first();

    if (!empty($cash)) {
        $cash->update([
            'supplier_id'=>$buy_bill->supplier_id,
            'reviewed'=> 1
        ]); 

        $safe_id = $cash->safe_id;
        $safe = Safe::FindOrFail($safe_id);
        $safe_balance_before = $safe->balance;
        $safe_balance_after = $safe_balance_before - $cash->amount;
        $safe->update([
            'balance' => $safe_balance_after
        ]);
    }
    if (!empty($bank_cash)) {
        $bank_cash->update([
            'supplier_id'=>$buy_bill->supplier_id,
            'reviewed'=> 1
        ]); 
        $bank_id = $bank_cash->bank_id;
        $bank = Bank::FindOrFail($bank_id);
        $bank_balance_before = $bank->bank_balance;
        $bank_balance_after = $bank_balance_before - $bank_cash->amount;
        $bank->update([
            'bank_balance' => $bank_balance_after
        ]);

    }

    if(!empty($bank_cash) || !empty($cash)){

        if(!empty($bank_cash)&&!empty($cash)){
        $paid = $cash->amount+$bank_cash->amount;
        }elseif(!empty($cash)){
               $paid = $cash->amount;
        }elseif(!empty($bank)){
             $paid = $bank_cash->amount;
        }

        $rest = $final_total-$paid;
        $buy_bill->update([
            'status' => 'done',
            'paid' => $paid,
            'rest' => $rest,
        ]);
        if (!empty($buy_bill->supplier_id)) {
            $supplier = Supplier::FindOrFail($buy_bill->supplier_id);
            $balance_before = $supplier->balance;
            $balance_after = $balance_before + $rest;
            $supplier->update([
                'balance' => $balance_after
                
            ]);
        }
    }elseif (empty($bank_cash) && empty($cash) ) {
        $rest = $final_total;
        if (!empty($buy_bill->supplier_id)) {
            $supplier = Supplier::FindOrFail($buy_bill->supplier_id);
            $balance_before = $supplier->balance;
            $balance_after = $balance_before + $rest;
            $supplier->update([
                'balance' => $balance_after
            ]);
            $buy_bill->update([
                'status' => 'done',
                'paid' => '0',
                'rest' => $rest,
            ]);
        }else{

            $buy_bill->update([
                'status' => 'done',
                'paid' => '0',
                'rest' => $rest,
            ]);

     }

    }

    }

    public function send($id)
    {
        $buy_bill = BuyBill::where('company_id',$company_id)->where('buy_bill_number', $id)->first();
        $url = 'https://' . request()->getHttpHost() . '/buy-bills/print/' . $id;
        $data = array(
            'body' => 'بيانات الفاتورة ',
            'url' => $url,
            'subject' => 'مرفق مع هذه الرسالة بيانات تفصيلية للفاتورة ',
        );
        Mail::to($buy_bill->supplier->supplier_email)->send(new sendingBuyBill($data));
        return redirect()->route('client.buy_bills.index')
            ->with('success', 'تم ارسال فاتورة المشتريات الى بريد المورد بنجاح');
    }

    public function edit($id){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $buy_bill=BuyBill::where('buy_bill_number',$id)->where('company_id',$company_id)->first();
        if(!$buy_bill){abort(404);}
        $open_buy_bill=BuyBill::findOrFail($buy_bill->id);
        $element = $open_buy_bill->element;
        $categories = $company->categories;
        $all_products = $company->products;
        $stores = $company->stores;
        $units = $company->units;
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $suppliers = Supplier::where('company_id', $company_id)->get();
        $user = Auth::user();
        $safes = $company->safes;
        $banks = $company->banks;
        $buy_bill_cash = BuyCash::where('company_id', $company_id)->where('bill_id', $open_buy_bill->buy_bill_number)->first();
        $buy_bill_bank_cash =BankBuyCash::where('company_id', $company_id)->where('bill_id', $open_buy_bill->buy_bill_number)->first(); 
        $check = BuyCash::where('company_id', $company_id)->get();
        if ($check->isEmpty()) {
            $pre_cash = 1;
        } else {
            $old_cash = Cash::where('company_id', $company_id)->max('cash_number');
            $pre_cash = ++$old_cash;
        }
        $pre_bill=0;
        
        return view('client.buy_bills.create',
        compact('company', 'buy_bill_cash', 'units', 'buy_bill_bank_cash', 'open_buy_bill', 'pre_cash', 'stores', 'safes', 'banks', 'suppliers', 'categories', 'extra_settings'
        ,'company_id', 'all_products', 'pre_bill','element'));
   
    }

    public function   editBuyBill($bill_id, $request){
        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $buy_bill = BuyBill::FindOrFail($bill_id);
        $rest = $buy_bill->rest;
        $elements = $buy_bill->elements;

        $this->refund_payment($buy_bill);


        foreach ($elements as $element) {
            $quantity = $element->quantity* $element->elements_unit->quantity;
            $product_id = $element->product_id;
            $product = Product::FindOrFail($product_id);
            $balance = $product->balance;
            $curr_balance = $balance - $quantity;
            $product->update([
                'balance' => $curr_balance
            ]);
        }
        
        $buy_bill->elements()->delete();

        for($i=0;count($request->product) > $i; $i++) {
            BuyBillElement::create([
                'company_id' => $company_id,
                'buy_bill_id' => $bill_id,
                'product_id' => $request->product[$i],
                'quantity' => $request->quantity[$i],
                'product_price' => $request->price[$i],
                'unit_id'  => $request->unit[$i],
                'quantity_price' => $request->quantity[$i]*$request->price[$i],
                
            ]);

            
        }
    }    

    public function refund_payment($buy_bill){


        $company_id = Auth::user()->company_id;
        $final_total = $buy_bill->final_total;
        $paid = $buy_bill->paid;
        $rest = $buy_bill->rest;

        $buy_cash = BuyCash::where('bill_id', $buy_bill->buy_bill_number)
        ->where('company_id', $company_id)
        ->first(); 

            if (!empty($buy_cash) && $buy_cash->reviewed == 1 ) {
                $safe_id = $buy_cash->safe_id;
                $safe = Safe::FindOrFail($safe_id);
                $safe_balance_before = $safe->balance;
                $safe_balance_after = $safe_balance_before + $buy_cash->amount;
                $safe->update([
                    'balance' => $safe_balance_after
                ]);
            }

            $bank_buy_cash = BankBuyCash::where('bill_id', $buy_bill->buy_bill_number)
                ->where('company_id', $company_id)
                ->first();

            if (!empty($bank_buy_cash) && $bank_buy_cash->reviewed == 1) {
                $bank_id = $bank_buy_cash->bank_id;
                $bank = Bank::FindOrFail($bank_id);
                $bank_balance_before = $bank->bank_balance;
                $bank_balance_after = $bank_balance_before + $bank_buy_cash->amount;
                $bank->update([
                    'bank_balance' => $bank_balance_after
                ]);
            }
        
    

    
    if (!empty($buy_bill->supplier_id)) {
        $supplier = Supplier::FindOrFail($buy_bill->supplier_id);
        $balance_before = $supplier->balance;
        $balance_after = $balance_before - $rest;
        $supplier->update([
            'balance' => $balance_after
        ]);
    }


    }

    public function destroy(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $buy_bill_number = $request->buy_bill_number;
        $buy_bill = BuyBill::where('company_id',$company_id)->where('buy_bill_number', $buy_bill_number)->first();
        $buy_bill->elements()->delete();
        $buy_bill->extras()->delete();
        $cash = BuyCash::where('bill_id', $buy_bill->buy_bill_number)
            ->where('company_id', $company_id)
            ->where('client_id', $buy_bill->client_id)
            ->where('supplier_id', $buy_bill->supplier_id)
            ->first();
        if (!empty($cash)) {
            $cash->delete();
        }
        $cash = BankBuyCash::where('bill_id', $buy_bill->buy_bill_number)
            ->where('company_id', $company_id)
            ->where('client_id', $buy_bill->client_id)
            ->where('supplier_id', $buy_bill->supplier_id)
            ->first();
        if (!empty($cash)) {
            $cash->delete();
        }
        $buy_bill->delete();
        return redirect()->route('client.buy_bills.create')
            ->with('success', 'تم حذف الفاتورة  بنجاح');
    }

    public function delete(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $bill_id = $request->id;
        $buy_bill = BuyBill::FindOrFail($bill_id);
        $elements = $buy_bill->elements;
        $extras = $buy_bill->extras;
        $final_total = $buy_bill->final_total;
        $paid = $buy_bill->paid;
        $rest = $buy_bill->rest;

        foreach ($elements as $element) {
            $quantity = $element->quantity;
            $product_id = $element->product_id;
            $product = Product::FindOrFail($product_id);
            $balance = $product->balance;
            $curr_balance = $balance - $quantity*$element->elements_unit->quantity;
            $product->update([
                'balance' => $curr_balance
            ]);
        }

        $buy_bill->elements()->delete();
        $buy_bill->extras()->delete();
        $cash = BuyCash::where('bill_id', $buy_bill->buy_bill_number)
            ->where('company_id', $company_id)
            ->where('supplier_id', $buy_bill->supplier_id)
            ->first();
        if (!empty($cash)) {
            $safe_id = $cash->safe_id;
            $safe = Safe::FindOrFail($safe_id);
            $safe_balance_before = $safe->balance;
            $safe_balance_after = $safe_balance_before + $cash->amount;
            $safe->update([
                'balance' => $safe_balance_after
            ]);

            $cash->delete();
        }
        $bank_cash = BankBuyCash::where('bill_id', $buy_bill->buy_bill_number)
            ->where('company_id', $company_id)
            ->where('supplier_id', $buy_bill->supplier_id)
            ->first();
        if (!empty($bank_cash)) {
            $bank_id = $bank_cash->bank_id;
            $bank = Bank::FindOrFail($bank_id);
            $bank_balance_before = $bank->bank_balance;
            $bank_balance_after = $bank_balance_before + $bank_cash->amount;
            $bank->update([
                'bank_balance' => $bank_balance_after
            ]);
            $bank_cash->delete();
        }
        $supplier = Supplier::FindOrFail($buy_bill->supplier_id);
        $balance_before = $supplier->balance;
        $balance_after = $balance_before - $rest;
        $supplier->update([
            'balance' => $balance_after
        ]);
        
        $buy_bill->update([
            'deleted' => '1'
        ]);
       
        return response()->json([
            'success' => 'تم حذف الفاتورة بنجاح',
            'final_total' => $final_total,
        ]);
    }

    public function search_filter(Request $request){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = $company->products;
        $buy_bills = BuyBill::active()->where('company_id', $company_id)->get();
        $suppliers = $company->suppliers;
        $clients = $company->clients;

        $suppliersArray=array();
        $invoiceIdArray=array();
        $clientsArray=array();

        /** supplier fillter **/
        if($request->supplier=="all"){
            $suppliersArray=[];
            $suppliersArray = $suppliers->pluck('id')->toArray();
        }else{
            $suppliersArray=[];
            array_push($suppliersArray, $request->supplier);
        }
        /** status fillter **/

        if($request->status=="all"){
            $statusArray=[];
            $statusArray = ['done', 'open'];
        }else{
            $statusArray=[];
            array_push($statusArray, $request->status);
        }

        /** client fillter **/
        if($request->clients=="all"){
            $clientsArray=[];
            $clientsArray = $clients->pluck('id')->toArray();
        }else{
            $clientsArray=[];
            array_push($clientsArray, $request->clients);
        }
        /** product fillter **/

        if($request->product_id=="all"){
            $invoiceIdArray = $company->buy_bills->pluck('id')->toArray();
        }else{
            $buy_bill_elements = BuyBillElement::where('product_id', $request->product_id)->get();
            $arr = array();
            foreach ($buy_bill_elements as $buy_bill_element) {
                $buy_bill = $buy_bill_element->BuyBill;
                $buy_bill_id = $buy_bill->id;
                array_push($arr, $buy_bill_id);
            }
            $invoiceIdArray = array_unique($arr);
        }

       
        $buy_bills = BuyBill::with('supplier','client')
        ->active()
        ->where('company_id', $company_id)  
        ->select(
        'id',
        'buy_bill_number',
        'supplier_id',
        'client_id',
        'time',
        'date',
        'status',
        'final_total')
        ->whereIn('id', $invoiceIdArray)
        ->whereIn('supplier_id', $suppliersArray)
        ->whereIn('client_id', $clientsArray)
        ->whereIn('status', $statusArray)
        ->orderBy('date','desc')
        ->orderBy('time','desc')
        ->where('deleted', 0)
        ->get();

        if($request->from_date && $request->to_date){
            $buy_bills = $buy_bills->whereBetween('date', [$request->from_date, $request->to_date]);
        }

     
        return   response()->json($buy_bills->toArray());
        
        }

  

    public function get_product_price(Request $request)
    {
        if(!empty($request->product_id)){
        $product = Product::FindOrFail($request->product_id);
        return response()->json([
            'purchasing_price' =>  $product->purchasing_price,
            'unit' =>  $product->unit->id,
            'unit_quantity' =>  $product->main_unit->quantity,

        ]);
        }else{
            return response()->json([
                'purchasing_price' =>  0,
            ]);
        }
    }

    public function get_supplier_details(Request $request)
    {
        $supplier_id = $request->supplier_id;
        $supplier = Supplier::FindOrFail($supplier_id);
        $category = $supplier->supplier_category;
        $balance_before = $supplier->balance;
        $supplier_national = $supplier->supplier_national;
        return response()->json([
            'status' => true,
            'category' => $category,
            'balance_before' => $balance_before,
            'supplier_national' => $supplier_national,
        ]);
    }

    public function delete_element(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $buy_bill=BuyBill::where('buy_bill_number',$request->buy_bill_number)->where('company_id',$company_id)->first();
        $element = BuyBillElement::where('buy_bill_id', $buy_bill->id)->where('product_id', $request->product_id)->where('unit_id',$request->unit)->first();
        if($request->status=='done'){
            $quantity = $element->quantity*$element->elements_unit->quantity;
            $product_id = $element->product_id;
            $product = Product::FindOrFail($product_id);
            $balance = $product->balance;
            $curr_balance = $balance - $quantity;
            $product->update([
                'balance' => $curr_balance
            ]);
        }
        $buy_bill_id = $element->buy_bill_id;
        $element->delete();

        return response()->json([
            'status' => true,
        ]);
    }

    public function checkInvoice(Request $request){
        
        $company_id = Auth::user()->company_id;
        $buy_bill = BuyBill::where('company_id',$company_id)->where('buy_bill_number', $request->buy_bill_number)->first();        
        $buy_bill->update([
            'status' => 'open'
        ]);
    
        return response()->json(['message' => 'تم تغير حالة الفاتورة إلي غير مكتملة', 'status' => true]);
        }    


    public function updatePriceAndQuuantity(Request $request)
    {
    $buy_bill= BuyBill::where('company_id',$request->company_id)->where('buy_bill_number',$request->buy_bill_number)->first();
    $element = BuyBillElement::where('company_id',$request->company_id)->where('unit_id',$request->unit_id)->where('product_id',$request->product_id)->where('buy_bill_id',$buy_bill->id)->first();
    if($buy_bill->status=='open'){
    $element->update([
        'quantity' => $request->quantity,
        'product_price' => $request->price,
        'quantity_price' => $request->price * $request->quantity,
    ]);

    return response()->json([
        'status' => true,
    ]);
    }
    }

    public function apply_discount(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $buy_bill_number = $request->buy_bill_number;
        $discount_type = $request->discount_type;
        $discount_value = $request->discount_value;
        $buy_bill = BuyBill::where('company_id',$company_id)->where('buy_bill_number', $buy_bill_number)->first();
        $extra_settings = ExtraSettings::where('company_id',$company_id)->where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $tax_value_added = $company->tax_value_added;
    
            $buy_bill_extra = BuyBillExtra::where('company_id',$company_id)->where('buy_bill_id', $buy_bill->id)
                ->where('action', 'discount')->first();
            if (empty($buy_bill_extra)) {
                $buy_bill_extra = BuyBillExtra::create([
                    'buy_bill_id' => $buy_bill->id,
                    'action' => 'discount',
                    'action_type' => $discount_type,
                    'value' => $discount_value,
                    'company_id' => $company_id,
                ]);
            } else {
                $buy_bill_extra->update([
                    'action_type' => $discount_type,
                    'value' => $discount_value,
                ]);
            }
            if($discount_type=='percent'){$disType='%';}else{$disType=$currency;}
            return response()->json(['status'=>true,'value'=>$discount_value, 'action_type' => $discount_type,'disType'=>$disType]);


        }

    

        public function apply_extra(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $buy_bill_number = $request->buy_bill_number;
        $extra_type = $request->extra_type;
        $extra_value = $request->extra_value;
        $buy_bill = BuyBill::where('company_id',$company_id)->where('buy_bill_number', $buy_bill_number)->first();
        $elements = BuyBillElement::where('company_id',$company_id)->where('buy_bill_id', $buy_bill->id)->get();
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $tax_value_added = $company->tax_value_added;
        
            $buy_bill_extra = BuyBillExtra::where('company_id',$company_id)->where('buy_bill_id', $buy_bill->id)
                ->where('action', 'extra')->first();
            if (empty($buy_bill_extra)) {
                $buy_bill_extra = BuyBillExtra::create([
                    'buy_bill_id' => $buy_bill->id,
                    'action' => 'extra',
                    'action_type' => $extra_type,
                    'value' => $extra_value,
                    'company_id' => $company_id,
                ]);
            } else {
                $buy_bill_extra->update([
                    'action_type' => $extra_type,
                    'value' => $extra_value,
                ]);
            }
            if($extra_type=='percent'){$exType='%';}else{$exType=$currency;}
            
        return response()->json(['status'=>true,'value'=>$extra_value,'action_type' => $extra_type,'exType'=>$exType]);
    }

    public function get_return(Request $request)
    {
        $buy_bill = BuyBill::FindOrFail($request->buy_bill_id);
        $element = BuyBillElement::FindOrFail($request->element_id);
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $suppliers = $company->suppliers;
        $products = $company->products;
        return view('client.buy_bills.return', compact('company', 'buy_bill', 'element', 'products', 'company_id', 'suppliers'));
    }

    public function post_return(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $data = $request->all();
        $data['company_id'] = $company_id;
        $data['client_id'] = Auth::user()->id;
        $return = BuyBillReturn::create($data);
        $element = BuyBillElement::FindOrFail($request->element_id);
        $product = Product::FindOrFail($request->product_id);
        $supplier = Supplier::FindOrFail($request->supplier_id);
        $product->update([
            'balance' => $request->after_return
        ]);
        $supplier->update([
            'balance' => $request->balance_after
        ]);
        $quantity_before_return = $element->quantity;
        $product_price_before_return = $element->product_price;

        $quantity_after_return = $quantity_before_return - $request->return_quantity;
        $product_price_after_return = $quantity_after_return * $product_price_before_return;
        if ($quantity_after_return == 0 || $product_price_after_return == 0) {
            $element->delete();
        } else {
            $element->update([
                'quantity' => $quantity_after_return,
                'quantity_price' => $product_price_after_return,
            ]);
        }

        return redirect()->route('client.buy_bills.returns');
    }

    public function get_returns()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $buy_bill_returns = $company->buy_bill_returns;
        return view('client.buy_bills.returns', compact('buy_bill_returns'));
    }

    public function redirect()
    {
        return redirect()->route('client.buy_bills.create')->with('success', 'تم انشاء فاتورة مشتريات بنجاح');
    }

    public function get_products(Request $request)
    {
        $store_id = $request->store_id;
        $products = Product::where('store_id', $store_id)->get();
        foreach ($products as $product) {
            echo "<option value='" . $product->id . "'>" . $product->product_name . "</option>";
        }
    }

    public function print($id)
    {
        $buy_bill = BuyBill::where('buy_bill_number', $id)->where('company_id',Auth::user()->company_id)->first();
        if(empty($buy_bill)){abort(404);}
        if($buy_bill->status=='done'){
        $company = Company::FindOrFail(Auth::user()->company_id); 
        $extra_settings =ExtraSettings::where('company_id', $company->id)->first();
        $currency = $extra_settings->currency;
        $tax_value_added = $company->tax_value_added;
        $cash = BuyCash::where('bill_id', $buy_bill->buy_bill_number)
        ->where('company_id', $company->id)
        ->where('supplier_id', $buy_bill->supplier_id)
        ->first();
         $bank_cash = BankBuyCash::where('bill_id', $buy_bill->buy_bill_number)
        ->where('company_id', $company->id)
        ->where('supplier_id', $buy_bill->supplier_id)
        ->first();
        return view('client.buy_bills.print', compact('buy_bill','extra_settings','company','tax_value_added','currency','cash','bank_cash'));
        }else{
            return "لا يمكن طباعة فاتورة غير مكتملة";
        }
    }
    
    public function edit_element(Request $request)
    {
        $element = BuyBillElement::FindOrFail($request->element_id);
        $product_id = $element->product_id;
        $product_price = $element->product_price;
        $quantity = $element->quantity;
        $quantity_price = $element->quantity_price;
        $unit_id = $element->unit_id;
        return response()->json([
            'product_id' => $product_id,
            'product_price' => $product_price,
            'quantity' => $quantity,
            'quantity_price' => $quantity_price,
            'unit_id' => $unit_id,
        ]);
    }
    public function get_supplier_invoices($id)
    { 
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);

        $products = $company->products;
        $buy_bills = BuyBill::where('company_id', $company_id)->where('status', 'done')->get();
        $suppliers = $company->suppliers;

        $supplier_k = Supplier::FindOrFail($id);
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;

        $supplier_buy_bills = BuyBill::where('company_id',$company_id)->where('supplier_id', $supplier_k->id)->get();

        return view('client.buy_bills.index', compact('currency', 'products', 'supplier_k', 'supplier_buy_bills', 'buy_bills', 'suppliers', 'company'));

    }


    public function update_total(Request $request){
        $company_id = Auth::user()->company_id;
        $buy_bill= BuyBill::where('company_id',$company_id)->where('buy_bill_number',$request->buy_bill_number)->first();
           
        if($buy_bill->status == "open"){

        $buy_bill->update([
                'final_total'=>$request->final_total,
                'rest'=>$request->final_total - $buy_bill->paid

            ]);
        }

    }

    public function getUnitPrice(Request $request){
        $company_id = auth()->user()->company_id;
        $product_unit = Product_unit::where('company_id',$company_id)->where('product_id',$request->product_id)->where('secondary_unit_id',$request->unit_id)->first();
        $product = Product::findOrFail($request->product_id);

        return response()->json([
            'purchasing_price'=>$product->purchasing_price,
            'quantity'=> $product_unit->quantity,
        ]);
    }


}


?>
