<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CarWashOwner;
use App\Models\OtherService;
use App\Models\CarOwnerCar;
use App\Models\OtherServiceReport;
use App\Models\OtherServiceReportToProduct;
use App\Models\CarOwner;
use App\Models\CurrencyMaster;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;

class CoOtherServicesController extends Controller
{
    public function __construct(){
    }


    public function list(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'co_id' => 'required',
                'per_page' => 'required',
                'total_viewed' => 'required'
            ],
            [
                'co_id.required' => 'Please enter Car Owner ID',
                'per_page.required' => 'Please enter per page',
                'total_viewed.required' => 'Please enter a total records viewed',
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $co_id = $request->input('co_id');
        $per_page = $request->input('per_page');
        $total_viewed = $request->input('total_viewed');

        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;

        $data = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time', 'cwo_master.cwo_company', 'cwo_master.cwo_isd', 'cwo_master.cwo_phone', 'currency_masters.symbol')
            ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where(function($query) use ($co_phone, $co_id) {
                $query->where('other_service_reports.phone', $co_phone)
                    ->orWhere('other_service_reports.co_id', $co_id);
            })
            ->orderBy('other_service_reports.id', 'desc');
        $dataCount = $data->count();
        $data = $data->limit($per_page)->offset($total_viewed);
        $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit; 

        $dataDisplay=[];
        $dataArray = [];
        if($data != '') {
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['name'] = $d->name;
                $dataDisplay['isd_code'] = $d->isd_code;
                $dataDisplay['phone'] = $d->phone;
                $dataDisplay['email'] = $d->email;
                $dataDisplay['cwo_company'] = $d->cwo_company;    
                if($d->cwo_phone != ''){
                    $dataDisplay['cwo_phone'] = '+' . $d->cwo_isd . $d->cwo_phone;
                } else {
                    $dataDisplay['cwo_phone'] = '';  
                }
                $dataDisplay['currency'] = $d->symbol;
                $dataDisplay['total_amount'] = $d->total_amount;
                $dataDisplay['payment_status_id'] = $d->payment_status;
                if($d->payment_status == 1) {
                    $dataDisplay['payment_status'] = 'Paid';
                } else {
                    $dataDisplay['payment_status'] = 'Not Paid';
                }
                $dataDisplay['payment_details'] = $d->payment_details;
                if($d->date != '') {
                    $dataDisplay['date']  = date("d/m/Y", strtotime($d->date));
                } else {
                    $dataDisplay['date']  = '';
                }
                if($d->time != '') {
                    $dataDisplay['time']  = date("h:i a", strtotime($d->time));
                } else {
                    $dataDisplay['time']  = '';
                }

                $services = OtherServiceReportToProduct::select('other_services.id', 'other_services.description as service', 'other_services.price as unit_price', 'other_service_report_to_products.quantity', 'other_service_report_to_products.total_price')
                            ->join('other_service_reports', 'other_service_report_to_products.other_service_report_id', 'other_service_reports.id')
                            ->join('other_services', 'other_service_report_to_products.other_service_id', 'other_services.id')
                            ->where('other_service_report_to_products.other_service_report_id', $d->id)
                            ->orderBy('other_service_report_to_products.id', 'asc')
                            ->get();
                $dataDisplay['services'] = $services;

                $dataArray[] = $dataDisplay;
            }
        }  
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'count' => $dataCount,
            'otherServiceList' => $dataArray
        ]); 
    }

    public function totalRecords(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'co_id' => 'required'
            ],
            [
                'co_id.required' => 'Please enter car owner id'
            ]
        );
        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }
        $co_id = $request->input('co_id');
        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;

        $totalProducts = OtherServiceReport::select(DB::raw('SUM(other_service_report_to_products.quantity) as total_quantity'))
                    ->join('other_service_report_to_products','other_service_reports.id','=','other_service_report_to_products.other_service_report_id')
                    ->where(function($query) use ($co_phone, $co_id) {
                        $query->where('other_service_reports.phone', $co_phone)
                            ->orWhere('other_service_reports.co_id', $co_id);
                    })
                    ->get();
        // echo "<pre>";print_r($totalProducts->toArray());exit;
        $totalProducts = $totalProducts[0]->total_quantity != '' ? $totalProducts[0]->total_quantity : 0;  

        $totalSpent = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_spent'))
            ->where('other_service_reports.payment_status', 1)
            ->where(function($query) use ($co_phone, $co_id) {
                        $query->where('other_service_reports.phone', $co_phone)
                            ->orWhere('other_service_reports.co_id', $co_id);
                    })
            ->get(); 
        // echo "<pre>";print_r($totalSpent->toArray());exit;    
        if($totalSpent[0]->total_spent != '') {
            $formatTotalSpent = formatCurrency($totalSpent[0]->total_spent);    
        } else {
            $formatTotalSpent = 0;
        }

        $getCurrency = OtherServiceReport::select('cwo_id')
            ->where(function($query) use ($co_phone, $co_id) {
                        $query->where('other_service_reports.phone', $co_phone)
                            ->orWhere('other_service_reports.co_id', $co_id);
                    })
            ->orderBy('other_service_reports.id', 'desc')
            ->take(1)
            ->get(); 
        // echo "<pre>";print_r($getCurrency->toArray());exit;  
        // echo $getCurrency->count();exit;  
        if($getCurrency->count() > 0){
            if($getCurrency[0]->cwo_id > 0){
                $cwo_id = $getCurrency[0]->cwo_id;
                $currencyDetail = CurrencyMaster::select('cwo_master.currency_id','currency_masters.symbol')
                    ->join('cwo_master','cwo_master.currency_id','=','currency_masters.id')
                    ->where('cwo_master.id', $cwo_id)
                    ->get();
                // echo $currencyDetail->count();exit;    
                // echo "<pre>";print_r($currencyDetail->toArray());exit;  
                if($currencyDetail->count() > 0) {
                    $currency = $currencyDetail[0]->symbol;    
                } else {
                    $currency = 'R';
                }  


                // $currency = 'calculate';
            } else {
                $currency = 'R';
            }
        } else {
            $currency = 'R';
        }    
        // echo $currency;exit;            

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'totalProducts' => $totalProducts,
            'totalSpentCount' => $formatTotalSpent,
            'currency' => $currency,
        ]);                            

    }


}
