<?php

namespace App\Http\Controllers\Admin;

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

class BillsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Bill::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 = Bill::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Bill::select('count(*) as allcount')
                ->whereHas('customer', function ($query) use ($searchValue){
                    $query->where('name','LIKE',"%$searchValue%");
                })
                ->orWhere('id', 'like', '%' . $searchValue . '%')
                ->count();

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


            $records = [];

            foreach($bills 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-success text-uppercase">' . __('Converted to Invoice') . '</span>';
                // }

                if($item->status == 1){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('مستحقة') . '</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.bills.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.bills.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

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

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

        }

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function myBills(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()->bills()->select('count(*) as allcount')->count();
            $totalRecordswithFilter = auth()->user()->bills()->select('count(*) as allcount')
                ->where('id', 'like', '%' . $searchValue . '%')
                ->count();

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


            $records = [];

            foreach($bills 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-success text-uppercase">' . __('Converted to Invoice') . '</span>';
                // }

                if($item->status == 1){
                    $status = '<span class="badge badge-soft-danger text-uppercase">' . __('مستحقة') . '</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.bills.datatable.my-button',[ 'item' => $item ])->render() ,
                ];
            }

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

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

        }

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


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

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


    public function store(Request $request)
    {
        # code...
        $this->authorize('create', Bill::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',
            '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('bills', 'public');
            $data['file'] = $file;
        }

        $bill = Bill::create($data);

        foreach($request->service_name as $key => $service)
        {
            $bill->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],
            ]);
        }

        $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.bills.index')->with('success',__('Added Done !'));
    }

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

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

    public function update(Request $request, Bill $bill)
    {
        # code...
        $this->authorize('update', $bill);
        $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',
            '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 = $bill->file;

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

        $bill->update($data);

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

        foreach($request->service_name as $key => $service)
        {
            $bill->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],
            ]);
        }

        $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.bills.index')->with('success',__('Updated Done !'));
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Bill $bill)
    {
        $this->authorize('delete', $bill);
        if($bill->file)
        Storage::disk('public')->delete($bill->file);
        $bill->delete();
        return redirect()->route('c-panel.bills.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) {
                $bill = Bill::FindOrFail($recordId);
                $this->authorize('delete', $bill);
                $this->delete($bill);
            }//end of for each
        }else{
            return redirect()->route('c-panel.bills.index')->with('error',__('Please Select Record Before Delete'));
        }

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

    private function delete(Bill $bill)
    {
        $this->authorize('delete', $bill);

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

}
