<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Mail\sendingQuotation;
use App\Models\BuyBill;
use App\Models\BuyCash;
use App\Models\Company;
use App\Models\ExtraSettings;
use App\Models\OuterClient;
use App\Models\PreSettings;
use App\Models\Product;
use App\Models\Quotation;
use App\Models\QuotationElement;
use App\Models\QuotationExtra;
use App\Models\SaleBill;
use App\Models\SaleBillElement;
use App\Models\SaleBillExtra;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class QuotationController 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' => ['destroy']]);
        $this->middleware('permission:تحويل عرض السعر إلي فاتورة بيع', ['only' => ['convert_to_salebill']]);

    }

    public function index()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $quotations = $company->quotations;
        $outer_clients = $company->outerClients;
        $products = $company->products;
        $clients = $company->clients;
        return view('client.quotations.index', compact('company', 'products', 'company_id', 'outer_clients', 'quotations', 'clients'));
    }
    public function search_filter(Request $request){
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $products = $company->products;
        $quotation = Quotation::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=[];
            $outerClientsArray = $outer_clients->pluck('id')->toArray();
            $outerClientCondetion = 1;
        }else{
            $outerClientsArray=[];
            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 = $quotation->pluck('id')->toArray();
        }else{
            $quotation_elements = QuotationElement::where('product_id', $request->product_id)->get();
            $arr = array();
            foreach ($quotation_elements as $sale_bill_element) {
                $sale_bill = $sale_bill_element->SaleBill;
                $sale_bill_id = $sale_bill->id;
                array_push($arr, $sale_bill_id);
            }
            $invoiceIdArray = array_unique($arr);
        }

       
        $quotation = Quotation::with(['outerClient','client'])
        ->active()
        ->whereIn('outer_client_id', $outerClientsArray)
        ->whereIn('id', $invoiceIdArray)
        ->whereIn('client_id', $clientsArray)
        ->whereIn('status', $statusArray)
        ->where('company_id', $company_id)
        ->orderBy('date','desc')
        ->orderBy('time','desc')
        ->where('deleted',0)
        ->get();

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

     
        return   response()->json($quotation->toArray());
        
        }
    
    public function send($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $quotation = Quotation::where('quotation_number', $id)->first();
        $tax_value_added = $company->tax_value_added;
        $elements = $quotation->elements;
        $sum = array();
        foreach ($elements as $element) {
            array_push($sum, $element->quantity_price);
        }
        $total = array_sum($sum);
        $previous_extra = QuotationExtra::where('quotation_id', $quotation->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 = QuotationExtra::where('quotation_id', $quotation->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;
        }
        $data = array(
            'quotation' => $quotation,
            'body' => 'بيانات عرض السعر',
            'elements' => $quotation->elements,
            'extras' => $quotation->extras,
            'subject' => 'مرفق مع هذه الرسالة بيانات تفصيلية لعرض السعر',
            'company' => $company,
            'after_total_all' => $after_total_all,
            'currency' => $currency,
        );
        Mail::to($quotation->outerClient->client_email)->send(new sendingQuotation($data));
        return redirect()->route('client.quotations.index')
            ->with('success', 'تم  ارسال عرض السعر  الى بريد العميل بنجاح');

    }

    public function show($id)
    {
        dd($id);
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $categories = $company->categories;
        $pre_settings = PreSettings::where('company_id', $company_id)->first();
        $all_products = Product::where('company_id', $company_id)->where('balance', '>', '0')->get();
        $stores = $company->stores;
        $units = $company->units;
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $outer_clients = OuterClient::where('company_id', $company_id)->get();
        $check = Quotation::all();

        if ($check->isEmpty()) {
            $pre_quotation = $pre_settings->pre_quotation;
        } else {
            $old_quotation = Quotation::where('company_id',$company_id)->latest()->value('quotation_number');
            $pre_quotation = ++$old_quotation;
        }

        $open_quotation = Quotation::with('extra')->where('company_id', $company_id)
        ->with('elements')
        ->where('client_id', Auth::user()->id)
        ->where('status', 'open')
        ->first();

        
        return view('client.quotations.create',
            compact('open_quotation','company', 'outer_clients', 'units', 'stores', 'company_id','extra_settings','all_products', 'pre_quotation'));
    }

    public function get_product_price(Request $request)
    {
        $product_id = $request->product_id;
        $outer_client_id = $request->outer_client_id;
        $product = Product::FindOrFail($product_id);
        $outer_client = OuterClient::FindOrFail($outer_client_id);
        $client_category = $outer_client->client_category;
        $sector_price = $product->sector_price;
        $wholesale_price = $product->wholesale_price;
        $balance = $product->balance;
        if ($client_category == "جملة") {
            $order_price = $wholesale_price;
        } elseif ($client_category == "قطاعى") {
            $order_price = $sector_price;
        }
        return response()->json([
            'order_price' => $order_price,
            'balance' => $balance . ' ' . $product->unit->unit_name
        ]);
    }

    public function cancel(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $quotation_number = $request->quotation_number;
        $quotation = Quotation::where('company_id',$company_id)->where('quotation_number', $quotation_number)->first();
        $quotation->elements()->delete();
        $quotation->extras()->delete();
        $quotation->delete();
        return redirect()->route('client.quotations.create')
            ->with('success', 'تم حذف الفاتورة  بنجاح');
    }

    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;
        
        $quotation = Quotation::where('company_id',$data['company_id'])->where('quotation_number',$data['quotation_number'])->first();
        if (empty($quotation)) {
        $data['status'] = 'open';
            $quotation = Quotation::create($data);
        } else {
            $quotation->update($data);
        }
        if($quotation->status=='open'){
        $product = Product::with('main_unit')->where('id',$request->product_id)->where('company_id',$data['company_id'])->first();
        $itemCheck = QuotationElement::where('company_id',$data['company_id'])->where('product_id',$request->product_id)->where('quotation_id',$quotation->id)->where('unit_id',$request->unit_id)->first();



        if(empty($itemCheck) || $product->is_product == 0){
            QuotationElement::create([
                'quotation_id'=> $quotation->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,
            ]);
        }

    }

}

    public function update_total(Request $request){

        $company_id = Auth::user()->company_id;
        $quotation= Quotation::where('company_id',$company_id)->where('quotation_number',$request->quotation_number)->first();
           
        if($quotation->status == "open"){

        $quotation->update([
                'final_total'=>$request->final_total,
            ]);
        }

    }

    public function updatePriceAndQuuantity(Request $request){

    $quotation= Quotation::where('company_id',$request->company_id)->where('quotation_number',$request->quotation_number)->first();
    $elements =  $quotation->elements->where('product_id',$request->product_id);
    $this_element = $elements->where('unit_id',$request->unit_id)->first();

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

    ]);

    }

    public function destroy_element(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $quotation = Quotation::where('company_id',$company_id)->where('quotation_number',$request->quotation_number)->first();
        $element = QuotationElement::where('product_id',$request->product_id)->where('unit_id',$request->unit_id)->where('quotation_id',$quotation->id)->first();
        $quotation_id = $element->quotation_id;
        $element->delete();
        return response()->json(['status'=>true,'message'=>'تم الحذف بنجاح']);
        
    }

    public function saveAll(Request $request){

        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $quotation = Quotation::where('company_id',$company_id)->where('quotation_number', $request->quotation_number)->first();

        $quotation->update([
            'status' => 'done'
        ]);
        

    }

    public function print($id){

        $quotation = Quotation::active()->where('quotation_number', $id)->where('company_id',Auth::user()->company_id)->first();
        if(empty($quotation)){abort(404);}
        if($quotation->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;

        return view('client.quotations.print', compact('quotation','extra_settings','company','tax_value_added','currency'));

        }

    }

    public function changeQuotation(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $data = $request->all();
        $quotation_number = $request->quotation_number;
        $quotation = Quotation::where('quotation_number', $quotation_number)->first();
        $quotation->update($data);
        echo "<p class='alert alert-sm alert-success text-center mt-2 mb-2'>تم حفظ البيانات بنجاح</p>";
    }

    public function apply_extra(Request $request)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $quotation_number = $request->quotation_number;
        $extra_type = $request->extra_type;
        $extra_value = $request->extra_value;
        $quotation = Quotation::where('company_id',$company_id)->where('quotation_number', $quotation_number)->first();
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $tax_value_added = $company->tax_value_added;
        
            $quotation_extra = QuotationExtra::where('company_id',$company_id)->where('quotation_id', $quotation->id)
                ->where('action', 'extra')->first();
            if (empty($quotation_extra)) {
                $quotation_extra = QuotationExtra::create([
                    'quotation_id' => $quotation->id,
                    'action' => 'extra',
                    'action_type' => $extra_type,
                    'value' => $extra_value,
                    'company_id' => $company_id,
                ]);
            } else {
                $quotation_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 apply_discount(Request $request){

        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $quotation_number = $request->quotation_number;
        $discount_type = $request->discount_type;
        $discount_value = $request->discount_value;
        $quotation = Quotation::where('company_id',$company_id)->where('quotation_number', $quotation_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;
    
            $quotation_extra = QuotationExtra::where('company_id',$company_id)->where('quotation_id', $quotation->id)
                ->where('action', 'discount')->first();
            if (empty($quotation_extra)) {
                $quotation_extra = QuotationExtra::create([
                    'quotation_id' => $quotation->id,
                    'action' => 'discount',
                    'action_type' => $discount_type,
                    'value' => $discount_value,
                    'company_id' => $company_id,
                ]);
            } else {
                $quotation_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 destroy(Request $request)
    {
        $quotation_number = $request->quotation_number;
        $quotation = Quotation::where('quotation_number', $quotation_number)->first();
        $quotation->elements()->delete();
        $quotation->extras()->delete();
        $quotation->delete();
        return redirect()->route('client.quotations.create')
            ->with('success', 'تم حذف عرض السعر بنجاح');
    }

    public function redirect()
    {
        return redirect()->route('client.quotations.create')->with('success', 'تم انشاء عرض السعر بنجاح');
    }


    public function get_products(Request $request)
    {
        $company_id = Auth::user()->company_id;
        if($request->store =="all"){
            $products = Product::where('company_id',$company_id)->select('id','product_name','code_universal','is_product')->get();
        }else{
            $products = Product::product()->where('company_id',$company_id)->where('store_id',$request->store)->select('id','product_name','code_universal','is_product')->get();
        }
        return response()->json(['products'=>$products]);
    }

    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';
        $quotation = Quotation::where('company_id',$data['company_id'])->where('quotation_number',$data['quotation_number'])->first();
        if (empty($quotation)) {
            $quotation = Quotation::create($data);
        } else {
            $quotation->update($data);
        }
            return response()->json([
                'status' => true,
                'category' => $category,
                'balance_before' => $balance_before,
                'client_national' => $outer_client_national,
            ]);
        }else{

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


    public function checkInvoice(Request $request){
        
        $company_id = Auth::user()->company_id;
        $quotation = Quotation::where('company_id',$company_id)->where('quotation_number', $request->quotation_number)->first();        
        $quotation->update([
            'status' => 'open'
        ]);
    
        return response()->json(['message' => 'تم تغير حالة عرض السعر إلي غير مكتمل', 'status' => true]);
        
        }   
    

    public function edit($id)
    {
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $open_quotation = Quotation::where('quotation_number', $id)->where('company_id', $company_id)->first();
        $stores = $company->stores;
        $units = $company->units;
        $extra_settings = ExtraSettings::where('company_id', $company_id)->first();
        $currency = $extra_settings->currency;
        $outer_clients = OuterClient::where('company_id', $company_id)->get();
        $pre_quotation = 0;

        return view('client.quotations.create',
            compact('open_quotation','units','stores',
                'extra_settings','outer_clients', 'company_id', 'company','pre_quotation'));
    }

    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;
        $quotation = Quotation::FindOrFail($bill_id);
        $quotation->extras->each->delete();
        $quotation->elements->each->delete();
        $quotation->update(['deleted' => 1]);
       
        return response()->json(['status' => true, 'message' => 'تم حذف عرض السعر بنجاح']);

    }


    public function update_element(Request $request)
    {
        $element_id = $request->element_id;
        $element = QuotationElement::FindOrFail($element_id);
        $element->update([
            'unit_id' => $request->unit_id,
            'product_id' => $request->product_id,
            'quantity' => $request->quantity,
            'quantity_price' => $request->quantity_price,
            'product_price' => $request->product_price,
        ]);
    }

    public function edit_element(Request $request)
    {
        $element = QuotationElement::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 convert_to_salebill(Request $request)
    {
        $id = $request->id;
        $quotation = Quotation::FindOrFail($id);
        $quotation_elements = $quotation->elements;
        $quotation_extras = $quotation->extras;


        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $client_id = Auth::user()->id;
        $pre_settings = PreSettings::where('company_id', $company_id)->first();


        $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;
        }

        $date = date('Y-m-d');
        $time = date('H:i:s');
        $status = "open";
        $paid = "0";

        $tax_value_added = $company->tax_value_added;
        $sum = array();
        foreach ($quotation_elements as $element) {
            array_push($sum, $element->quantity_price);
        }
        $total = array_sum($sum);
        $previous_extra = QuotationExtra::where('quotation_id', $quotation->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 = QuotationExtra::where('quotation_id', $quotation->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;
        }
        $final_total = $after_total_all;
        $rest = $final_total;

        $saleBill = SaleBill::create([
            'company_id' => $company_id,
            'client_id' => $client_id,
            'outer_client_id' => $quotation->outer_client_id,
            'sale_bill_number' => $pre_bill,
            'date' => $date,
            'time' => $time,
            'status' => $status,
            'final_total' => $final_total,
            'paid' => $paid,
            'rest' => $rest,
        ]);

        foreach ($quotation_elements as $element) {
            $salebill_element = SaleBillElement::create([
                'sale_bill_id' => $saleBill->id,
                'company_id' => $company_id,
                'product_id' => $element->product_id,
                'product_price' => $element->product_price,
                'quantity' => $element->quantity,
                'quantity_price' => $element->quantity_price,
                'unit_id' => $element->unit_id
            ]);
        }
        foreach ($quotation_extras as $extra) {
            $saleBill_extra = SaleBillExtra::create([
                'company_id' => $company_id,
                'sale_bill_id' => $saleBill->id,
                'action' => $extra->action,
                'action_type' => $extra->action_type,
                'value' => $extra->value,
            ]);
        }

        return response()->json([
            'message'=>'تم تحويل عرض السعر الى فاتورة مبيعات',
            'status'=>true,
            'url'=>route('client.sale_bills.edit',$pre_bill)
        ]);
    }
}

?>
