<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bill;
use App\Models\Offer;
use App\Models\User;
use App\Models\WebsiteSetting;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class OffersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Offer::class);
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = Offer::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Offer::select('count(*) as allcount')
                ->whereHas('customer', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhere('id', 'like', '%' . $searchValue . '%')
                ->count();

            $offers = Offer::select('offers.*')
                ->whereHas('customer', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhere('id', 'like', '%' . $searchValue . '%')
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('offers.id', 'desc')
                ->get();


            $records = [];

            foreach($offers as $item)
            {
                $status = '';
                if($item->status == 0){
                    $status = '<span class="badge badge-soft-primary text-uppercase">' . __('New Offer') . '</span>';
                }else if($item->status == 1){
                    $status = '<span class="badge badge-soft-info text-uppercase">' . __('Under Review') . '</span>';
                }else if($item->status == 2){
                    $status = '<span class="badge badge-soft-warning text-uppercase">' . __('Under Update') . '</span>';
                }else if($item->status == 3){
                    $status = '<span class="badge badge-soft-success text-uppercase">' . __('Accepted') . '</span>';
                }else if($item->status == 4){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Rejected') . '</span>';
                }else if($item->status == 5){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Canceled') . '</span>';
                }else if($item->status == 6){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Certified') . '</span>';
                }

                if($item->currancy == 0) {
                    $currancy = '$';
                } else if ($item->currancy == 1) {
                    $currancy = 'SAR';
                } else if ($item->currancy == 2) {
                    $currancy = 'ILS';
                }

                $records[] = [
                    'record_select' =>view('admin.offers.datatable.record   ',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'customer' => $item->customer->name,
                    'date' => $item->date,
                    'end_date' => $item->end_date ?? __('Not Entered'),
                    'status' => $status,
                    'totel' => $item->totel . ' ' . $currancy,
                    'actions' => view('admin.offers.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }

        return view('admin.offers.index');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function myOffers(Request $request)
    {
        $this->authorize('client', User::class);
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = auth()->user()->offers()->select('count(*) as allcount')->count();
            $totalRecordswithFilter = auth()->user()->offers()->select('count(*) as allcount')
                ->where('id', 'like', '%' . $searchValue . '%')
                ->count();

            $offers = auth()->user()->offers()->select('offers.*')
                ->where('id', 'like', '%' . $searchValue . '%')
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('offers.id', 'desc')
                ->get();


            $records = [];

            foreach($offers as $item)
            {
                $status = '';
                if($item->status == 0){
                    $status = '<span class="badge badge-soft-primary text-uppercase">' . __('New Offer') . '</span>';
                }else if($item->status == 1){
                    $status = '<span class="badge badge-soft-info text-uppercase">' . __('Under Review') . '</span>';
                }else if($item->status == 2){
                    $status = '<span class="badge badge-soft-warning text-uppercase">' . __('Under Update') . '</span>';
                }else if($item->status == 3){
                    $status = '<span class="badge badge-soft-success text-uppercase">' . __('Accepted') . '</span>';
                }else if($item->status == 4){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Rejected') . '</span>';
                }else if($item->status == 5){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Canceled') . '</span>';
                }else if($item->status == 6){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('Certified') . '</span>';
                }

                if($item->currancy == 0) {
                    $currancy = '$';
                } else if ($item->currancy == 1) {
                    $currancy = 'SAR';
                } else if ($item->currancy == 2) {
                    $currancy = 'ILS';
                }

                $records[] = [
                    'id' => $item->id,
                    'date' => $item->date,
                    'end_date' => $item->end_date ?? __('Not Entered'),
                    'status' => $status,
                    'totel' => $item->totel . ' ' . $currancy,
                    'actions' => view('admin.offers.datatable.my-buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }

        return view('admin.offers.my-offers');
    }

    public function create()
    {
        # code...
        $this->authorize('create', Offer::class);
        $customers = User::where('role_id',0)->latest()->get();

        return view('admin.offers.create',[
            'customers' => $customers,
        ]);
    }

    public function store(Request $request)
    {
        # code...
        $this->authorize('create', Offer::class);
        $request->validate([
            'service_totel' => 'array|required',
            'service_totel.*' => 'required|numeric',
            'totel' => 'required|numeric',
            'service_tax' => 'array|required',
            'service_tax.*' => 'nullable|numeric',
            'service_discount' => 'array|required',
            'service_discount.*' => 'nullable|numeric',
            'service_period' => 'array|required',
            'service_period.*' => 'required|string',
            'service_price' => 'array|required',
            'service_price.*' => 'required|numeric',
            'service_name' => 'array|required',
            'service_name.*' => 'required|string',
            'customer_id' => 'required|exists:users,id',
            'file' => 'nullable|mimes:png,jpg,pdf,jpeg',
            'description' => 'nullable',
            'note' => 'nullable',
            'date' => 'required|date',
            'end_date' => 'nullable|date',
            'currancy' => 'required|in:0,1,2',
        ]);

        $data = $request->except(['file', 'service_tax', 'service_discount', 'service_totel', 'service_period', 'service_price', 'service_name']);
        $data['status'] = 0;

        $file = null;

        if($request->hasFile('file') && $request->file('file')->isValid())
        {
            $file = $request->file('file')->store('offers', 'public');
            $data['file'] = $file;
        }

        $offer = Offer::create($data);

        foreach($request->service_name as $key => $service)
        {
            $offer->services()->create([
                'name' => $service,
                'period' => $request->service_period[$key],
                'price' => $request->service_price[$key],
                'discount' => $request->service_discount[$key] ?? 0,
                'tax' => $request->service_tax[$key] ?? 0,
                'totel' => $request->service_totel[$key],
            ]);
        }

        return redirect()->route('c-panel.offers.index')->with('success',__('Added Done !'));
    }

    public function edit(Offer $offer)
    {
        # code...
        $this->authorize('update', $offer);
        $customers = User::where('role_id',0)->latest()->get();

        return view('admin.offers.edit',[
            'customers' => $customers,
            'offer' => $offer,
        ]);
    }

    public function update(Request $request, Offer $offer)
    {
        # code...
        $this->authorize('update', $offer);
        $request->validate([
            'service_totel' => 'array|required',
            'service_totel.*' => 'required|numeric',
            'totel' => 'required|numeric',
            'service_tax' => 'array|required',
            'service_tax.*' => 'nullable|numeric',
            'service_discount' => 'array|required',
            'service_discount.*' => 'nullable|numeric',
            'service_period' => 'array|required',
            'service_period.*' => 'required|string',
            'service_price' => 'array|required',
            'service_price.*' => 'required|numeric',
            'service_name' => 'array|required',
            'service_name.*' => 'required|string',
            'customer_id' => 'required|exists:users,id',
            'file' => 'nullable|mimes:png,jpg,pdf,jpeg',
            'description' => 'nullable',
            'note' => 'nullable',
            'date' => 'required|date',
            'end_date' => 'nullable|date',
            'currancy' => 'required|in:0,1,2',
        ]);

        $data = $request->except(['file', 'service_tax', 'service_discount', 'service_totel', 'service_period', 'service_price', 'service_name']);
        $data['status'] = 0;

        $file = $offer->file;

        if($request->hasFile('file') && $request->file('file')->isValid())
        {
            Storage::disk('public')->delete($offer->file);
            $file = $request->file('file')->store('offers', 'public');
            $data['file'] = $file;
        }

        $offer->update($data);

        $offer->services()->delete();

        foreach($request->service_name as $key => $service)
        {
            $offer->services()->create([
                'name' => $service,
                'period' => $request->service_period[$key],
                'price' => $request->service_price[$key],
                'discount' => $request->service_discount[$key] ?? 0,
                'tax' => $request->service_tax[$key] ?? 0,
                'totel' => $request->service_totel[$key],
            ]);
        }

        return redirect()->route('c-panel.offers.index')->with('success',__('Updated Done !'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Offer $offer)
    {
        $this->authorize('delete', $offer);
        if($offer->file)
        Storage::disk('public')->delete($offer->file);
        $offer->delete();
        return redirect()->route('c-panel.offers.index')->with('success',__('Deleted Done !'));
    }

    public function bulkDelete()
    {
        // dd(json_decode(request()->record_ids));
        if(count(json_decode(request()->record_ids)) != 0){
            foreach (json_decode(request()->record_ids) as $recordId) {
                $offer = Offer::FindOrFail($recordId);
                $this->authorize('delete', $offer);
                $this->delete($offer);
            }//end of for each
        }else{
            return redirect()->route('c-panel.offers.index')->with('error',__('Please Select Record Before Delete'));
        }

        return redirect()->route('c-panel.offers.index')->with('success',__('Selected  Deleted Done !'));
    }// end of bulkDelete

    private function delete(Offer $offer)
    {
        $this->authorize('delete', $offer);

        if($offer->file)
        Storage::disk('public')->delete($offer->file);
        $offer->delete();
    }

    public function updateStatus(Request $request, Offer $offer)
    {
        # code...
        $this->authorize('update', $offer);
        $request->validate([
            'status' => 'required|in:0,1,2,3,4,5,6',
        ]);
        if($request->status != 6){
            $offer->update([
                'status' => $request->status
            ]);
            return redirect()->route('c-panel.offers.index')->with('success',__('Updated Done !'));
        } else {
            $bill = Bill::create([
                'customer_id' => $offer->customer_id,
                'date' => $offer->date,
                'end_date' => $offer->end_date,
                'currancy' => $offer->currancy,
                'file' => $offer->file,
                'totel' => $offer->totel,
                'status' => 0,
            ]);

            foreach ($offer->services as $key => $value) {
                # code...
                $bill->services()->create([
                    'name' => $value->name,
                    'price' => $value->price,
                    'period' => $value->period,
                    'discount' => $value->discount,
                    'tax' => $value->tax,
                    'totel' => $value->totel,
                ]);
            }
            $offer->update([
                'status' => 6,
            ]);

            $mail_data1 = [
                'recipient' => $bill->customer->email,
                'fromEmail' => env('MAIL_FROM_ADDRESS','ahmer631998@gmail.com'),
                'fromName' => WebsiteSetting::first()->title ?? '',
                'bill' => $bill,
                'title' => __('Financial due bill'),
            ];
            Mail::send('admin.bills.email-template',$mail_data1,function($message) use ($mail_data1){
                $message->to($mail_data1['recipient'])
                        ->from($mail_data1['fromEmail'],$mail_data1['fromName'])
                        ->subject($mail_data1['title']);
            });
            return redirect()->route('c-panel.offers.index')->with('success',__('Converted to Invoice!'));

        }

    }
}
