<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Mail\sendingSaleBill;
use App\Models\Bank;
use App\Models\BankCash;
use App\Models\OuterClient;
use App\Models\SaleBillReturn;
use App\Models\Cash;
use App\Models\Company;
use App\Models\ExtraSettings;
use App\Models\PreSettings;
use App\Models\Product;
use App\Models\Safe;
use App\Models\BuyCash;
use App\Models\Product_unit;
use App\Models\SaleBill;
use App\Models\SaleBillElement;
use App\Models\SaleBillExtra;
use App\Models\Screen;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Artisan;

class SaleBillController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:عرض فواتير المبيعات', ['only' => ['index']]);
        $this->middleware('permission:إضافة فاتورة مبيعات', ['only' => ['create']]);
        $this->middleware('permission:حذف فاتورة مبيعات', ['only' => ['destroy']]);
        $this->middleware('permission:تعديل فاتورة مبيعات', ['only' => ['edit']]);

    }

    public function index()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $sale_bills = SaleBill::active()->where('company_id', $company_id)->get();
        $outer_clients = $company->outerClients;
        $products = $company->products;
        $clients = $company->clients;


        return view('client.sale_bills.index', compact('company', 'products', 'company_id', 'outer_clients', 'sale_bills','clients'));
    }
    
    public function search_filter(Request $request){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = $company->products;
        $sale_bills = SaleBill::active()->where('company_id', $company_id)->orderBy('date','desc')->get();
        $outer_clients = $company->outerClients;
        $clients = $company->clients;
        $outerClientCondetion = "";

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


        if ($request->outerClient == "all") {
            $outerClientsArray[] = null;

        } elseif ($request->filled('clients')) {
            array_push($outerClientsArray, $request->outerClient);
    }
        

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

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


        if($request->product_id =="all"){
            $invoiceIdArray = $sale_bills->pluck('id')->toArray();
        }else{
            $sale_bill_elements = SaleBillElement::where('product_id',$request->product_id)->get();
            $arr = array();
            foreach ($sale_bill_elements as $sale_bill_element) {

                array_push($arr, $sale_bill_element->sale_bill_id);
                
            }
            $invoiceIdArray = array_unique($arr);
        }

        // return $invoiceIdArray;
       
        $sale_bills = SaleBill::with('outerClient','client')
        ->active()
        ->where('company_id', $company_id)
        ->select(  
        'id',
        'sale_bill_number',
        'outer_client_id',
        'client_id',
        'time',
        'date',
        'status',
        'final_total',
        'updated_at',
        'client_id')
        ->where(function ($query) use ($outerClientsArray) {
            if (in_array(null, $outerClientsArray)) {
                
            } else {
                // إذا كان عميل محدد، قم بتضمين فقط فواتير هذا العميل
                $query->whereIn('outer_client_id', $outerClientsArray);
            }
        })
        ->whereIn('status', $statusArray)
        ->whereIn('id', $invoiceIdArray)
        ->whereIn('client_id', $clientsArray)
        ->orderBy('date','desc')
        ->orderBy('time','desc')
        ->where('deleted',0)
        ->get();

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

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

    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();
        $outer_clients = OuterClient::where('company_id', $company_id)->get();
        $pre_settings = PreSettings::where('company_id', $company_id)->first();
        $screen = Screen::where('company_id', $company_id)->first();
        if($screen->sales_type == 0){$inv_type = 'create-pos';}else{$inv_type ='create';}
        $user = Auth::user();
        $safes = $company->safes;
        $banks = $company->banks;
        $check = SaleBill::where('company_id',$company_id)->get();
        if ($check->isEmpty()) {
            $pre_bill = $pre_settings->pre_bill;
        } else {
            $old_pre_bill = SaleBill::where('company_id',$company_id)->latest()->value('sale_bill_number');
            $pre_bill = ++$old_pre_bill;
        }

        $check = Cash::where('company_id', $company_id)->get();
        if ($check->isEmpty()) {
            $pre_cash = $pre_settings->pre_cash;
        } else {
            $old_cash = Cash::where('company_id', $company_id)->max('cash_number');
            $pre_cash = ++$old_cash;
        }

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

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

        if ($allowToBill) {
            $step = SaleBill::where('company_id', $company_id)
                ->with('elements')
                ->where('client_id', $client_id)
                ->where('status', 'open')
                ->first();

            if (!empty($step)) {
                $open_sale_bill = $step;
                $element =SaleBillElement::where('sale_bill_id',$step->id)->first();
                $sale_bill_cash = Cash::where('company_id', $company_id)->where('bill_id', $step->sale_bill_number)->first();
                $sale_bill_bank_cash = BankCash::where('company_id', $company_id)->where('bill_id', $step->sale_bill_number)->first();

            } else {
                $open_sale_bill = null;
                $element = null;
                $sale_bill_cash = null;
                $sale_bill_bank_cash = null;

            }

            return view('client.sale_bills.'.$inv_type,
            compact('company', 'sale_bill_cash', 'units', 'sale_bill_bank_cash', 'open_sale_bill', 'pre_cash', 'stores', 'safes', 'banks', 'outer_clients', 'categories', 'extra_settings'
                , 'company_id', 'pre_bill','element'));

            
        } else {

                return redirect()->route('client.home')->with('error', 'باقتك الحالية لا تسمح بالمزيد من فواتير المبيعات');
        }
        
    }


    public function edit($id){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $sale_bill=SaleBill::where('sale_bill_number',$id)->where('company_id',$company_id)->first();
        $open_sale_bill=SaleBill::findOrFail($sale_bill->id);
        $element = $open_sale_bill->element;
        $categories = $company->categories;
        $all_products = $company->products;
        $stores = $company->stores;
        $units = $company->units;
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $outer_clients = OuterClient::where('company_id', $company_id)->get();
        $user = Auth::user();
        $safes = $company->safes;
        $banks = $company->banks;
        $sale_bill_cash = Cash::where('company_id', $company_id)->where('bill_id', $open_sale_bill->sale_bill_number)->first();
        $sale_bill_bank_cash = BankCash::where('company_id', $company_id)->where('bill_id', $open_sale_bill->sale_bill_number)->first(); 
        $check = Cash::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.sale_bills.create',
        compact('company', 'sale_bill_cash', 'units', 'sale_bill_bank_cash', 'open_sale_bill', 'pre_cash', 'stores', 'safes', 'banks', 'outer_clients', 'categories', 'extra_settings'
        ,'company_id', 'all_products', 'pre_bill','element'));
   
    }
    
    public function store_cash_outer_clients(Request $request)
    {
        
        $this->validate($request, [
            'cash_number' => 'required',
//            'outer_client_id' => 'required',
            'amount' => 'required',
            'date' => 'required',
            'time' => 'required',
        ]);
        $data = $request->all();
        $company_id = $data['company_id'];
        $data['client_id'] = Auth::user()->id;
        $amount = $data['amount'];
        $bill_id = $request->bill_id;
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number', $bill_id)->first();
        $outer_client_id = $data['outer_client_id'];
        if (!empty($sale_bill->outer_client_id)) {
            $outer_client = OuterClient::FindOrFail($outer_client_id);
            $balance_before = $outer_client->balance;
            $balance_after = $balance_before - $amount;
            $data['balance_before'] = $balance_before;
            $data['balance_after'] = $balance_after;
        } else {
            $data['balance_before'] = 0;
            $data['balance_after'] = 0;
        }

        $cash = Cash::where('bill_id', $request->bill_id)
        ->where('company_id', $company_id)
        ->first();

        $bank_cash = BankCash::where('bill_id', $request->bill_id)
        ->where('company_id', $company_id)
        ->first();

        $payment_method = $data['payment_method'];
        if ($payment_method == "cash") {

            if (empty($cash)) {
                $cash = Cash::create($data);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => 'غير مسموح لك .. تم الدفع من قبل'
                ]);
            }
        } else {
            if (empty($bank_cash)) {
                $bank_cash = BankCash::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;
                $amount = $cash->amount ;
                $cash_number = $cash->id ;
            } elseif ($payment_method == "bank") {
                $pay_method = 'دفع بنكى شبكة ';
                $bank = $bank_cash->bank->bank_name;
                $amount = $bank_cash->amount ;
                $cash_number = $bank_cash->id ;
            }

                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($sale_bill->status == "open"){

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

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

                }


            return response()->json([
                'status' => true,
                'message' => 'تم تسجيل الدفع بنجاح' ,
                'cash_number' => $cash_number,
                '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 = Cash::FindOrFail($cash_id);
            if($cash->salebill->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->salebill->update([
                    'paid' => $cash->salebill->paid - $cash->amount,
                ]);

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

            $cash->delete();
            

        } elseif ($payment_method == "bank") {
            $bank_cash = BankCash::FindOrFail($cash_id);
            if($bank_cash->bill->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->bill->update([
                    'paid' => $bank_cash->bill->paid - $bank_cash->amount,
                ]);

                if($bank_cash->bill->status == 'open'){
                    $bank_cash->bill->update([
                        'rest' => $bank_cash->bill->final_total - $bank_cash->bill->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;
        
        $SaleBill = SaleBill::where('company_id',$data['company_id'])->where('sale_bill_number',$data['sale_bill_number'])->first();
        if (empty($SaleBill)) {
        $data['status'] = 'open';
            $SaleBill = SaleBill::create($data);
        } else {
            $SaleBill->update($data);
        }
        if($SaleBill->status=='open'){
        $product = Product::with('main_unit')->where('id',$request->product_id)->where('company_id',$data['company_id'])->first();
        $itemCheck = SaleBillElement::where('company_id',$data['company_id'])->where('product_id',$request->product_id)->where('sale_bill_id',$SaleBill->id)->where('unit_id',$request->unit_id)->first();



        if(empty($itemCheck) || $product->is_product == 0){
            SaleBillElement::create([
                'sale_bill_id'=> $SaleBill->id,
                'company_id'=> $request->company_id,
                'product_id'=>$request->product_id,
                'quantity'=>$request->quantity,
                'product_price'=>$request->product_price,
                'unit_id'=>$request->unit_id,
                'quantity_price'=>$request->quantity_price,
    
            ]);
        }else{
            $itemCheck->update([
                'quantity'=>$itemCheck->quantity + $request->quantity,
            ]);

            $itemCheck->update([
                'quantity_price'=>$itemCheck->product_price * $itemCheck->quantity,
            ]);
        }


    }

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

    }
    public function delete_element(Request $request)
    {
       $sale_bill= SaleBill::where('company_id',Auth::user()->company_id)->where('sale_bill_number',$request->invoice_number)->first();
       
        $element_id = $request->element_id;
        $element = SaleBillElement::where('sale_bill_id',$sale_bill->id)->where('product_id',$request->product_id)->where('unit_id',$request->unit_id)->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
            ]);

        }
        $element->delete();

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

    public function updatePriceAndQuuantity(Request $request){

    $sale_bill= SaleBill::where('company_id',$request->company_id)->where('sale_bill_number',$request->sale_bill_number)->first();
    $product = Product::where('id',$request->product_id)->where('company_id',$request->company_id)->first();
    $product_unit = Product_unit::where('product_id',$request->product_id)->where('secondary_unit_id',$request->unit_id)->first();
    $elements =  $sale_bill->elements->where('product_id',$request->product_id);
    $this_element = $elements->where('unit_id',$request->unit_id)->first();
    $ThisInvoiceItemQuantity = 0;
    if($product->is_product==0){
        $this_element->update($request->all());
        return response()->json(['status'=>true]); 
    }

    if($request->quantity <= 0 || empty($request->quantity)){

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

    }

    $quantityByUnit = $request->quantity * $product_unit->quantity ;
    foreach($elements as $element){

        $ThisInvoiceItemQuantity += $element->quantity * $element->elements_unit->quantity;

    }
    
    
    if($sale_bill->status=='open'){

        $availbale = $product->balance - $ThisInvoiceItemQuantity + $this_element->quantity * $this_element->elements_unit->quantity  ;

    }elseif($sale_bill->status=='done'){
        $availbale = $product->balance + $this_element->quantity * $this_element->elements_unit->quantity  ;
    }


        if($quantityByUnit <= $availbale && $sale_bill->status=='open'){

            $this_element->update([
                'product_price'=>$request->price,
                'quantity'=>$request->quantity,
                'quantity_price'=> $request->quantity * $request->price,
    
            ]);

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


        }elseif($quantityByUnit > $availbale){

                $availbale = $availbale ;

        return response()->json([
        'status'=>false,'message'=>'الكمية المدخلة أكبر من الكمية الموجودة',
        'quantity'=>round($availbale,3),'last_quantity' => $this_element->quantity,
        'unit_name'=>$product_unit->secondary_unit->unit_name]);

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


    

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

    public function saveAll(Request $request)
    {

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number', $request->sale_bill_number)->first();
        

        $sale_bill->update([
            'state' => 'done',
            'final_total'=> $request->total,
            'tax'=>$request->tax,
            'subtotal'=>$request->subtotal,
        ]);
        

        if($request->status=='done'){
               $this->editSaleBill($sale_bill->id,$request);
        }

        $sale_bill->update([
            'outer_client_id' => $request->outer_client_id,
        ]);

        $this->check_bill_paid($sale_bill,$request);

        $elements = $sale_bill->elements;

        foreach ($elements as $element) {
            $product = Product::FindOrFail($element->product_id);
            $old_product_balance = $product->balance;
            $new_product_balance = $old_product_balance - $element->quantity* $element->elements_unit->quantity;
            if($product->is_product==1){
                $product->update([
                    'balance' => $new_product_balance
                ]);

            }
        }
        
    }

    public function check_bill_paid($sale_bill,$request){
        $company_id = Auth::user()->company_id;
        $final_total = $sale_bill->final_total;

        $cash = Cash::where('bill_id', $sale_bill->sale_bill_number)
            ->where('company_id', $company_id)
            ->first();

            $bank_cash = BankCash::where('bill_id', $sale_bill->sale_bill_number)
            ->where('company_id', $company_id)
            ->first();

        if (!empty($cash)) { 
            $cash->update([
                'outer_client_id'=>$sale_bill->outer_client_id,
                'reviewed'=> 1
            ]); 
            $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
            ]);
        }
        if (!empty($bank_cash)) {
            $bank_cash->update([
                'outer_client_id'=>$sale_bill->outer_client_id,
                'reviewed'=> 1
            ]); 
            $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
            ]);
            
        }

        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;
            
            if(!empty($sale_bill->outer_client_id)) {
                $outer_client = OuterClient::FindOrFail($sale_bill->outer_client_id);
                $balance_before = $outer_client->balance;
                $balance_after = $balance_before + $rest;
                $outer_client->update([
                    'balance' => $balance_after
                ]);
            }

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

        }elseif (empty($bank_cash) &&  empty($cash) ) {

            $rest = $sale_bill->final_total;

            if (!empty($sale_bill->outer_client_id)) {
                $outer_client = OuterClient::FindOrFail($sale_bill->outer_client_id);
                $balance_before = $outer_client->balance;
                $balance_after = $balance_before + $rest;
                $outer_client->update([
                    'balance' => $balance_after
                ]);
                
            }
                $sale_bill->update([
                    'status' => 'done',
                    'paid' => '0',
                    'rest' => $rest,
                ]);

          
        }
    }
    public function editSaleBill($bill_id, $request){
        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $sale_bill = SaleBill::FindOrFail($bill_id);
        $elements = $sale_bill->elements;


        $this->refund_payment($sale_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
            ]);
        }
        $sale_bill->elements()->delete();

        for($i=0;count($request->product) > $i; $i++) {

            SaleBillElement::create([
                'company_id' => $company_id,
                'sale_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 checkInvoice(Request $request){
        
    $company_id = Auth::user()->company_id;
    $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number', $request->sale_bill_number)->first();        
    $sale_bill->update([
        'status' => 'open'
    ]);

    return response()->json(['message' => 'تم تغير حالة الفاتورة إلي غير مكتملة', 'status' => true]);
    }    
    

    public function send($id)
    {
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number', $id)->first();
        $url = 'https://' . request()->getHttpHost() . '/sale-bills/print/' . $id;
        $data = array(
            'body' => 'بيانات الفاتورة ',
            'url' => $url,
            'subject' => 'مرفق مع هذه الرسالة بيانات تفصيلية للفاتورة ',
        );
        Mail::to($sale_bill->outerClient->client_email)->send(new sendingSaleBill($data));
        return redirect()->route('client.sale_bills.index')
            ->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;
        $sale_bill = SaleBill::FindOrFail($bill_id);
        $elements = $sale_bill->elements;
        $extras = $sale_bill->extras;
        $final_total = $sale_bill->final_total;
        $paid = $sale_bill->paid;
        $rest = $sale_bill->rest;

        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
            ]);
        }

        $sale_bill->elements()->delete();
        $sale_bill->extras()->delete();

        $cash = Cash::where('bill_id', $sale_bill->sale_bill_number)
        ->where('company_id', $company_id)
        ->where('client_id', $sale_bill->client_id)
        ->where('outer_client_id', $sale_bill->outer_client_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 = BankCash::where('bill_id', $sale_bill->sale_bill_number)
        ->where('company_id', $company_id)
        ->where('client_id', $sale_bill->client_id)
        ->where('outer_client_id', $sale_bill->outer_client_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();
    }
    if (!empty($sale_bill->outer_client_id)) {
        $outer_client = OuterClient::FindOrFail($sale_bill->outer_client_id);
        $balance_before = $outer_client->balance;
        $balance_after = $balance_before - $rest;
        $outer_client->update([
            'balance' => $balance_after
        ]);
    }

        $sale_bill->update([
            'deleted' => 1,
            'status' => 'done'
        ]);
        return  response()->json(['success' => 'تم حذف الفاتورة بنجاح','status'=>true]);
        }

    public function edit_element(Request $request)
    {
        $element = SaleBillElement::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 refund_payment($sale_bill){

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

        $cash = Cash::where('bill_id', $sale_bill->sale_bill_number)
        ->where('company_id', $company_id)
        ->first(); 

            if (!empty($cash) && $cash->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
                ]);
            }

            $bank_cash = BankCash::where('bill_id', $sale_bill->sale_bill_number)
                ->where('company_id', $company_id)
                ->first();

            if (!empty($bank_cash) && $bank_cash->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($sale_bill->outer_client_id)) {
        $outer_client = OuterClient::FindOrFail($sale_bill->outer_client_id);
        $balance_before = $outer_client->balance;
        $balance_after = $balance_before - $rest;
        $outer_client->update([
            'balance' => $balance_after
        ]);
    }


    

    }

   
    public function get_product_price(Request $request)
    {
        $product_id = $request->product_id;
        if(!empty($product_id)){ 
        $product = Product::FindOrFail($product_id);
        $sale_bill = SaleBill::where('company_id',Auth::user()->company_id)->where('sale_bill_number', $request->sale_bill_number)->first();
        $wholesale_price = $product->wholesale_price;
        $sector_price = $product->sector_price;
        $balance = $product->balance;

        if($product->is_product==0){
            $balance = 999999999;
        }else{
        if (!empty($sale_bill)) {
                $elements = $sale_bill->elements->where('product_id', $product_id);
            if (!$elements->isempty()) {
                $sum = 0;
                foreach ($elements as $element) {
                    $sum += $element->quantity * $element->elements_unit->quantity;
                }
                if($sale_bill->status=='open'){
                $balance = $balance - $sum;
                }else{
                    $balance = $balance ; //plus item add to salebill item
                }
            }
        }
    }
        
        return response()->json([
            'product_name' => $product->product_name,
            'wholesale_price' => $wholesale_price,
            'sector_price' => $sector_price,
            'purchasing_price' => $product->purchasing_price,
            'balance' => round($balance,3),  
            'unit_name'=>$product->unit->unit_name,
            'unit'=>$product->unit_id,
            'is_product'=>$product->is_product,
            'unit_quantity'=>$product->main_unit->quantity,
            'category'=>$product->category->category_name,
            'store'=>$product->store ? $product->store->store_name : 'لا يوجد مخزن',
            
        ]);
    }else{
        return 0;
    }
}
    public function get_edit_product_price(Request $request)
    {
        $product = Product::FindOrFail($request->product_id);

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

    public function get_outer_client_details(Request $request)
    {
        if(!empty($request->outer_client_id)){
        $outer_client = OuterClient::FindOrFail($request->outer_client_id);
        $category = $outer_client->client_category;
        $balance_before = $outer_client->balance;
        $outer_client_national = $outer_client->client_national;
        }
        $data = $request->all();
        $data['company_id'] = Auth::user()->company_id;
        $data['client_id'] = Auth::user()->id;
        $data['status'] = 'open';
        $SaleBill = SaleBill::where('company_id',$data['company_id'])->where('sale_bill_number',$data['sale_bill_number'])->first();
        if (empty($SaleBill)) {
            $SaleBill = SaleBill::create($data);
        } else {
                if($SaleBill->status=='open'){                    
                    $SaleBill->update($data);
                }
        }
        if(!empty($request->outer_client_id)){
        return response()->json([
            'status' => true,
            'category' => $category,//
            'balance_before' => $balance_before,
            'client_national' => $outer_client_national,
        ]);
    }else{
        return response()->json(['status'=>false]);
    }
    }

    public function apply_discount(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $sale_bill_number = $request->sale_bill_number;
        $discount_type = $request->discount_type;
        $discount_value = $request->discount_value;
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number', $sale_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;
    
            $sale_bill_extra = SaleBillExtra::where('company_id',$company_id)->where('sale_bill_id', $sale_bill->id)
                ->where('action', 'discount')->first();
            if (empty($sale_bill_extra)) {
                $sale_bill_extra = SaleBillExtra::create([
                    'sale_bill_id' => $sale_bill->id,
                    'action' => 'discount',
                    'action_type' => $discount_type,
                    'value' => $discount_value,
                    'company_id' => $company_id,
                ]);
            } else {
                $sale_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);
        $sale_bill_number = $request->sale_bill_number;
        $extra_type = $request->extra_type;
        $extra_value = $request->extra_value;
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number', $sale_bill_number)->first();
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $tax_value_added = $company->tax_value_added;
        
            $sale_bill_extra = SaleBillExtra::where('company_id',$company_id)->where('sale_bill_id', $sale_bill->id)
                ->where('action', 'extra')->first();
            if (empty($sale_bill_extra)) {
                $sale_bill_extra = SaleBillExtra::create([
                    'sale_bill_id' => $sale_bill->id,
                    'action' => 'extra',
                    'action_type' => $extra_type,
                    'value' => $extra_value,
                    'company_id' => $company_id,
                ]);
            } else {
                $sale_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)
    {
        $sale_bill = SaleBill::FindOrFail($request->sale_bill_id);
        $element = SaleBillElement::FindOrFail($request->element_id);
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $outer_clients = $company->outerClients;
        $products = $company->products;
        return view('client.sale_bills.return', compact('company', 'sale_bill', 'element', 'products', 'company_id', 'outer_clients'));
    }
    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 = SaleBillReturn::create($data);
        $element = SaleBillElement::FindOrFail($request->element_id);
        $product = Product::FindOrFail($request->product_id);
        $sale_bill = $element->SaleBill;
        $product->update([
            'balance' => $request->after_return
        ]);
        if (!empty($sale_bill->outer_client_id)) {
            $outer_client = OuterClient::FindOrFail($request->outer_client_id);
            $outer_client->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,
            ]);
        }

        $elements = $sale_bill->elements;
        $tax_value_added = $company->tax_value_added;
        $sum = array();
        foreach ($elements as $element) {
            array_push($sum, $element->quantity_price);
        }
        $total = array_sum($sum);
        $previous_extra = SaleBillExtra::where('company_id',$company_id)->where('sale_bill_id', $sale_bill->id)
            ->where('action', 'extra')->first();
        if (!empty($previous_extra)) {
            $previous_extra_type = $previous_extra->action_type;
            $previous_extra_value = $previous_extra->value;
            if ($previous_extra_type == "percent") {
                $previous_extra_value = $previous_extra_value / 100 * $total;
            }
            $after_discount = $total + $previous_extra_value;
        }
        $previous_discount = SaleBillExtra::where('company_id',$company_id)->where('sale_bill_id', $sale_bill->id)
            ->where('action', 'discount')->first();
        if (!empty($previous_discount)) {
            $previous_discount_type = $previous_discount->action_type;
            $previous_discount_value = $previous_discount->value;
            if ($previous_discount_type == "percent") {
                $previous_discount_value = $previous_discount_value / 100 * $total;
            }
            $after_discount = $total - $previous_discount_value;

        }
        if (!empty($previous_extra) && !empty($previous_discount)) {
            $after_discount = $total - $previous_discount_value + $previous_extra_value;
        } else {
            $after_discount = $total;
        }
        if (isset($after_discount) && $after_discount != 0) {
            $percentage = ($tax_value_added / 100) * $after_discount;
            $after_total_all = $after_discount + $percentage;
        } else {
            $percentage = ($tax_value_added / 100) * $total;
            $after_total_all = $total + $percentage;
        }
        $sale_bill->update([
            'final_total' => $after_total_all
        ]);
        return redirect()->route('client.sale_bills.returns');
    }
    public function get_returns()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $sale_bill_returns = $company->sale_bill_returns;
        return view('client.sale_bills.returns', compact('sale_bill_returns'));
    }
    public function redirect()
    {
        return redirect()->route('client.sale_bills.create')->with('success', 'تم انشاء فاتورة مبيعات بنجاح');
    }
    public function print($id)
    {
        $sale_bill = SaleBill::active()->where('sale_bill_number', $id)->where('company_id',Auth::user()->company_id)->first();
        if(empty($sale_bill)){abort(404);}
        if($sale_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 = Cash::where('bill_id', $sale_bill->sale_bill_number)
        ->where('company_id', $company->id)
        ->where('outer_client_id', $sale_bill->outer_client_id)
        ->first();
         $bank_cash = BankCash::where('bill_id', $sale_bill->sale_bill_number)
        ->where('company_id', $company->id)
        ->where('outer_client_id', $sale_bill->outer_client_id)
        ->first();
        return view('client.sale_bills.print', compact('sale_bill','extra_settings','company','tax_value_added','currency','cash','bank_cash'));
        }else{
            return "لا يمكن طباعة فاتورة غير مكتملة";
        }
    }


    public function get_client_invoices($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);

        $products = $company->products;
        $sale_bills = SaleBill::where('company_id', $company_id)->where('status', 'done')->get();
        $outer_clients = $company->outerClients;
        $outer_client_k = OuterClient::FindOrFail($id);
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;

        $outer_client_sale_bills = SaleBill::where('company_id',$company_id)->where('outer_client_id', $id)->get();

        return view('client.sale_bills.index', compact('currency', 'products', 'outer_client_k', 'outer_client_sale_bills', 'sale_bills', 'outer_clients', 'company'));
    }


    public function get_product_by_inv(Request $request){
        
        $company_id = Auth::user()->company_id;

        if($request->store =="all"){

            $products = Product::with(['main_unit_quantity','unit'])->where('company_id',$company_id)->select('id','product_name','code_universal','is_product','product_pic','sector_price','unit_id')->get();

        }else{

            $products = Product::with(['main_unit_quantity','unit'])->product()->where('company_id',$company_id)->where('store_id',$request->store)->select('id','product_name','code_universal','is_product','product_pic','sector_price','unit_id')->get();

        }

        return response()->json(['products'=>$products]);
    }

    public function check_payment(Request $request){

        $company_id = Auth::user()->company_id;
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number',$request->sale_bill_number)->first();
        if($sale_bill->paid >= $sale_bill->final_total && $sale_bill->paid !== 0 && $sale_bill->final_total !== 0 && $sale_bill->final_total !== null && $sale_bill->paid !== null ){
            
            return response()->json(['status'=>true]);

        }else{
            return response()->json(['status'=>false]);
        }

    }

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

        $sale_bill->update([
                'final_total'=>$request->final_total,
                'rest'=>$request->final_total - $sale_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([
            'product_sector_price'=>$product->sector_price,
            'product_wholesale_price'=>$product->wholesale_price,
            'quantity'=> $product_unit->quantity,
            'balance' => $product->balance,
        ]);
    }

    public function check_sale_bill_elment(Request $request){

        $company_id = auth()->user()->company_id;
        $sale_bill = SaleBill::where('company_id',$company_id)->where('sale_bill_number',$request->sale_bill_number)->first();
        $error = array();
        
        foreach($sale_bill->elements as $element){

                $product = Product::findOrFail($element->product_id)->where('is_product',1)->first();
                $item_quantity = $element->quantity * $element->elements_unit->quantity;
                $availbale = $product->balance * $product->main_unit->quantity;

                if($sale_bill->status=='open'){
                    $availbale = $availbale;
                }elseif($sale_bill->status=='done'){
                    $availbale = $item_quantity + $availbale;
                }

                if($item_quantity <= $availbale){
                    // array_push($error,['status'=>true]); 

                }else{
                    array_push($error,$element->id); 
                }

        }

        return response()->json(['error'=>$error]);

    }

}

?>
