<?php

namespace App\Http\Controllers\AdminPanel;

use App\Http\Controllers\Controller;
use App\Models\CarWashOwner;
use App\Models\CurrencyMaster;
use App\Models\SubscriptionDetail;
use App\Models\CwoSubscription;
use App\Models\User;
use App\Models\WashCategory;
use App\Models\WashDetail;
use App\Models\CleanerMaster;
use App\Models\Loyalty;
use App\Models\CwoPasscode;
use Illuminate\Http\Request;
use App\Services\CarWashOwnerService;

use File;
use App\Models\Demo;
use App\Traits\Upload;
use Illuminate\Support\Facades\Storage;

class CarWashOwnerController extends Controller
{
    protected $carwashownerService;
    use Upload; //add this trait

    public function __construct(CarWashOwnerService $carwashownerService)
    {
        $this->carwashownerService = $carwashownerService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $cwo_lists = $this->carwashownerService->getCarWashOwner();
            $iTotalRecords = $cwo_lists->count();

            $iDisplayLength = isset($_REQUEST['length']) ? intval($_REQUEST['length']) : 0;
            $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength;
            $iDisplayStart = isset($_REQUEST['start']) ? intval($_REQUEST['start']) : 0;
            $sEcho = isset($_REQUEST['draw']) ? intval($_REQUEST['draw']) : 0;
            $rowNumber = $iDisplayStart + 1;
            // dd($cwo_lists);
            foreach ($cwo_lists as $t) {
                // print_r($cwo_lists);exit;
                $created_at = date("d-m-Y", strtotime($t->created_at));
                if($t->end_date != '') {
                    $end_date = date("d-m-Y", strtotime($t->end_date));
                } else {
                    $end_date = '';
                }
                $amount = '0';
                if($t->is_paid == 1){
                    if($t->free_trial == 1 && $t->cwo_subscription_id == 0){
                        $subscription_status = 'Free Trial';
                    } else {
                        // $subscription_status = 'Active';
                        // $cwo_subscription_data = CwoSubscription::where('id', $t->cwo_subscription_id)->select('type', 'amount')->first(); 
                        $sub_detail = CwoSubscription::find($t->cwo_subscription_id);
                        if($sub_detail != ''){
                            $amount =  'R'.$sub_detail->amount;
                            if($sub_detail->type == 1){
                                $subscription_status = '30 days' ;
                            }
                            if($sub_detail->type == 2){
                                $subscription_status = '365 days' ;  
                            }
                            if($sub_detail->type == 3){
                                $subscription_status = '90 days' ;  
                            }
                        } else {
                            $amount =  '';
                            $subscription_status = '';
                        }
                        
                    }
                } else {
                    $subscription_status = 'Inactive';
                    $amount =  '';
                }

                $edit_url = route('admin.cwo.edit', ['id' => $t->id]);
                $user_url = route('admin.cu.user.list', ['cwoid' => $t->id]);
                $banner_url = route('admin.banner.list', ['cwoid' => $t->id]);

                $actionColumnHtml = "<td class='product-action'>
                    <a href =$edit_url ><span class='action-edit'><i class='feather icon-edit' title='Edit'></i></span></a>
                    <a href =$user_url ><span class='action-edit'><i class='feather icon-user' title='Users'></i></span></a>
                    <a href =$banner_url ><span class='action-edit'><i class='feather icon-image' title='Banner'></i></span></a>
                    <a href ='javascript:void(0);' data-id =$t->id class = 'delete_cwo'><span class='action-delete' title='Delete'><i class='feather icon-trash'></i></span></a>
                    <a href ='javascript:void(0);' data-id =$t->id class = 'renew_cwo' data-company ='$t->cwo_company'><span class='action-renew' title='Renew'><i class='feather icon-refresh-cw'></i></span></a>
                </td>";

                $is_active = $t->is_active == 1 ? 'checked' : '';

                $status = " <div class='custom-control custom-switch custom-switch-success mr-2 mb-1'>
                <input type='checkbox'  class='custom-control-input change_status' id='customSwitch_$t->id' $is_active data-id=$t->id >
                <label class='custom-control-label' for='customSwitch_$t->id'></label>
                </div>";



                $records["data"][] = array(
                    $rowNumber,
                    // '',
                    '<div class="product-name">' . $t->cwo_name . '</div>',
                    '<div class="product-name">' . $t->cwo_email . '</div>',
                    '<div class="custom-icon-center">' . '+' . $t->cwo_isd . $t->cwo_phone . '</div>',
                    '<div class="custom-icon-center">' . $t->account_no . '</div>',
                    '<div class="custom-icon-center">' . $t->cwo_company . '</div>',
                    '<div class="custom-icon-center">' . $created_at . '</div>',
                    '<div class="custom-icon-center">' . $subscription_status . '- ' . $amount . '</div>',
                    '<div class="custom-icon-center">' . $end_date . '</div>',
                    $status,
                    '<span class="custom-btn">' . $actionColumnHtml . '</span>'

                );
                $rowNumber++;
            }

            $records["draw"] = $sEcho;
            $records["recordsTotal"] = $iTotalRecords;
            $records["recordsFiltered"] = $iTotalRecords;
            return json_encode($records);
        }
        $dataBag['subscription_detail'] = SubscriptionDetail::orderBy('id', 'asc')->get();
        // echo "<pre>";print_r($dataBag['subscription_detail']->toArray());exit;
        return view('carwashowner.list', $dataBag);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $dataBag['currencies'] = CurrencyMaster::orderBy('id', 'asc')->get();
        $dataBag['subscription_detail'] = SubscriptionDetail::orderBy('id', 'asc')->get();
        // echo "<pre>";print_r($dataBag['subscription_detail']->toArray());exit;
        return view('carwashowner.create', $dataBag);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //

        // $request->validate([
        //     'cwo_logo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust validation rules as needed
        // ]);

        /*$cwo_logo = '';
        if ($request->hasFile('cwo_logo')) {
            $cwo_logo = $request->file('cwo_logo');
            $imageName = time() . '.' . $cwo_logo->extension();
            // $cwo_logo->move(public_path('upload'), $imageName);

            $cwo_logo = $this->UploadFile($request->file('cwo_logo'), 'car_wash_owner');
        }*/
        // dd($cwo_logo);
        $account_no = generateUniqueNumberCWO();
        // echo $account_no;exit;
        $cwo_logo = '';
        if ($request->hasFile('cwo_logo')) {
            $cwo_logo = time() . '.' . $request->file('cwo_logo')->extension();
            $path = $request->file('cwo_logo')->move(public_path('images/cwo/'), $cwo_logo);
        }

        if($request->address != ''){
            $address = getLatLongFromAddress($request->address);
            // print_r($address);
            $lat = $address['lat'];
            $long = $address['long'];
        } else {
            $lat = '';
            $long = '';
        }
        // echo $lat . ' - ' . $long;exit;
        
        $data = [
            'cwo_name' => $request->cwo_name,
            'cwo_isd' => $request->cwo_isd,
            'cwo_phone' => $request->cwo_phone,
            'cwo_email' => $request->cwo_email,
            'cwo_company' => $request->cwo_company,
            'cwo_business_details' => $request->cwo_business_details,
            'is_active' => $request->has('is_active') ? $request->is_active : 1,
            'cwo_logo' => $cwo_logo,
            'currency_id' => $request->currency_id,
            'address' => $request->address,
            'allow_prebooking' => $request->allow_prebooking,
            'is_paid'=> 0,
            'account_no'=> $account_no,
            'lat'=> $lat,
            'long'=> $long,
        ];
        $cwo_create = CarWashOwner::create($data);
        // print_r($cwo_create->toarray());exit;

        // echo $request->subscription_detail_id;exit;
        if($request->subscription_detail_id != ''){
            $today = date('Y-m-d');
            $time = strtotime(date("Y-m-d"));
            if($request->subscription_detail_id == 'monthly'){
                $end_date = date("Y-m-d", strtotime("+1 month", $time));
                $type = 1;
                $amount = 250;
            }
            if($request->subscription_detail_id == 'yearly'){
                $end_date = date("Y-m-d", strtotime("+1 year", $time));
                $type = 2;
                $amount = 2900;
            }
            if($request->subscription_detail_id == 'quarterly'){
                $end_date = date("Y-m-d", strtotime("+3 month", $time));
                $type = 3;
                $amount = 700;
            }
            // echo $end_date;exit;

            $subscription_data = [
                'subscription_detail_id' => 1,
                'cwo_id' => $cwo_create['id'],
                'start_date' => $today,
                'end_date' => $end_date,
                'type' => $type,
                'amount' => $amount,
                'status' => 1,
            ];
            $subs_create = CwoSubscription::create($subscription_data);

            $cwo_subscription_id = $subs_create['id'];
            $cwoDetails = CarWashOwner::findOrFail($cwo_create['id']);
            $cwoDetails->update([
                'cwo_subscription_id'=> $cwo_subscription_id,
                'start_date'=> $today,
                'end_date'=> $end_date,
                'is_paid'=> 1
                ]);
        }


        return redirect()->back()->with('success', 'User Created Successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Request $request, $id)
    {

        $data['cwo_user'] = CarWashOwner::find($id);
        $data['currencies'] = CurrencyMaster::orderBy('id', 'asc')->get();
        $data['subscription_detail'] = SubscriptionDetail::orderBy('id', 'asc')->get();
        $data['cwo_subscription'] = CwoSubscription::where('cwo_id', $id)->where('status', 1)->orderBy('id', 'desc')->take(1)->get();
        // dd($data['cwo_user'] );
        return view('carwashowner.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
        $item = CarWashOwner::findOrFail($id);

        $cwo_logo = $item->cwo_logo;
        // dd($request->all());
        // dd(Storage::disk('public')->exists($cwo_logo),$cwo_logo);
        /*if ($request->hasFile('cwo_logo')) {
            if ($cwo_logo && Storage::disk('public')->exists($cwo_logo)) {
                $this->deleteFile($cwo_logo);
            }
            $cwo_logo = $request->file('cwo_logo');

            $cwo_logo = $this->UploadFile($request->file('cwo_logo'), 'car_wash_owner');
        }*/
        if ($request->hasFile('cwo_logo')) {
            $cwo_logo = time() . '.' . $request->file('cwo_logo')->extension();
            $path = $request->file('cwo_logo')->move(public_path('images/cwo/'), $cwo_logo);
        }

        if($request->address != ''){
            $address = getLatLongFromAddress($request->address);
            // print_r($address);
            $lat = $address['lat'];
            $long = $address['long'];
        } else {
            $lat = '';
            $long = '';
        }

        $data = [
            'cwo_name' => $request->cwo_name,
            'cwo_isd' => $request->cwo_isd,
            'cwo_phone' => $request->cwo_phone,
            'cwo_email' => $request->cwo_email,
            'cwo_company' => $request->cwo_company,
            'cwo_business_details' => $request->cwo_business_details,
            'is_active' => $request->has('is_active') ? $request->is_active : 1,
            'cwo_logo' => $cwo_logo,
            'currency_id' => $request->currency_id,
            'address' => $request->address,
            'allow_prebooking' => $request->allow_prebooking,
            'lat'=> $lat,
            'long'=> $long,
        ];
        $item->update($data);

        if($request->subscription_detail_id != ''){
            $today = date('Y-m-d');
            $time = strtotime(date("Y-m-d"));
            if($request->subscription_detail_id == 'monthly'){
                $end_date = date("Y-m-d", strtotime("+1 month", $time));
                $type = 1;
                $amount = 250;
            }
            if($request->subscription_detail_id == 'yearly'){
                $end_date = date("Y-m-d", strtotime("+1 year", $time));
                $type = 2;
                $amount = 2900;
            }
            if($request->subscription_detail_id == 'quarterly'){
                $end_date = date("Y-m-d", strtotime("+3 month", $time));
                $type = 3;
                $amount = 700;
            }
            // echo $end_date;exit;

            $subscription_data = [
                'subscription_detail_id' => 1,
                'cwo_id' => $id,
                'start_date' => $today,
                'end_date' => $end_date,
                'type' => $type,
                'amount' => $amount,
                'status' => 1,
            ];
            $subs_create = CwoSubscription::create($subscription_data);

            $cwo_subscription_id = $subs_create['id'];
            $item->update([
                'cwo_subscription_id'=> $cwo_subscription_id,
                'start_date'=> $today,
                'end_date'=> $end_date,
                'is_paid'=> 1
                ]);
        }

        return redirect()->back()->with('success', 'User Updated Successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request)
    {
        //
        $id = $request->id;
        // dd($id);

        /*$userCount = User::where('cwo_id', $id)->where('is_active', 1)->count();
        // echo $userCount;exit;
        if($userCount > 0){
            return response()->json(['message' => 'This CWO has active users associated with it. You can not delete it.', 'status' => 2], 200);    
        }

        $washCategoryCount = WashCategory::where('cwo_id', $id)->where('is_active', '!=', 3)->count();
        // echo $userCount;exit;
        if($washCategoryCount > 0){
            return response()->json(['message' => 'This CWO has wash categories associated with it. You can not delete it.', 'status' => 2], 200);    
        }

        $item = CarWashOwner::find($id)->delete();*/

        $wash_record = WashDetail::where('cwo_id', $id);
        $wash_record->delete();

        $wash_category_record = WashCategory::where('cwo_id', $id);
        $wash_category_record->delete();

        $cleaner_record = CleanerMaster::where('cwo_id', $id);
        $cleaner_record->delete();

        $user_record = User::where('cwo_id', $id);
        $user_record->delete();

        $loyalty_record = Loyalty::where('cwo_id', $id);
        $loyalty_record->delete();

        $passcode_record = CwoPasscode::where('cwo_id', $id);
        $passcode_record->delete();

        $item = CarWashOwner::find($id)->delete();


        return response()->json(['message' => 'User deleted successfully', 'status' => 1], 200);
    }
    public function delete_image(Request $request)
    {
        $id = $request->id;
        $item = CarWashOwner::findOrFail($id);
        $cwo_logo = $item->cwo_logo;

        if ($cwo_logo && Storage::disk('public')->exists($cwo_logo)) {
            $this->deleteFile($cwo_logo);
        }

        $data = [
            'cwo_logo' => '',
        ];
        $item->update($data);
        return response()->json(['message' => 'User status changed successfully', 'status' => 1], 200);
    }
    public function downloadList(Request $request)
    {
        $selectedColumn = ['cwo_name', 'cwo_phone', 'cwo_email', 'cwo_company', 'cwo_business_details', 'is_active'];
        $csv_header = ['Name', 'Phone', 'Email', 'Company', 'Business Details', 'Status'];

        $cwo_lists = $this->carwashownerService->getCarWashOwner($selectedColumn, $request);

        $_data = $cwo_lists->toArray();
        $csv_data = [$csv_header, ...$_data];

        csvDownlaod($csv_data, 'cwo_list.csv');
    }

    public function status_change_ajax(Request $request)
    {
        try {
            $user_data = CarWashOwner::where('id', $request->id)->first();
            if ($user_data != null) {
                $user_data->is_active = $request->status;
                $user_data->save();

                return response()->json(['message' => 'User status changed successfully', 'status' => 1], 200);
            } else {
                return response()->json(['message' => 'User not found', 'status' => 0], 401);
            }
        } catch (exception $e) {
        }
    }

    public function renewInfo(Request $request)
    {
        //
        $cwo_id = $request->cwo_id;
        $subscription_detail_id = $request->subscription_detail_id;
        // echo $cwo_id . ' - ' . $subscription_detail_id;exit;
        $item = CarWashOwner::findOrFail($cwo_id);

        if($subscription_detail_id != ''){
            $today = date('Y-m-d');
            $time = strtotime(date("Y-m-d"));
            $getCwo = CarWashOwner::where('id', $cwo_id)->select('start_date', 'end_date', 'free_trial')->first();

            // if($subscription_detail_id == 'monthly'){
            //     $end_date = date("Y-m-d", strtotime("+1 month", $time));
            //     $type = 1;
            //     $amount = 300;
            // }
            $cwo_subscription = CwoSubscription::where('cwo_id', $cwo_id)->where('status', 1)->orderBy('id', 'desc')->take(1)->get();
            if(isset($cwo_subscription) && count($cwo_subscription)>0){ // if previous subscription exist
                if($subscription_detail_id == 'monthly'){
                    if($getCwo->end_date == ''){
                        $start_date = date("Y-m-d");
                        $end_date = date("Y-m-d", strtotime("+1 month", $time));
                    } else {
                        $start_date = date("Y-m-d", strtotime("+1 day", strtotime($getCwo->end_date)));
                        $end_date = date('Y-m-d', strtotime('+1 month', strtotime($getCwo->end_date)));
                    }
                    $type = 1;
                    $amount = 300;
                    
                }
                if($subscription_detail_id == 'quarterly'){
                    if($getCwo->end_date == ''){
                        $start_date = date("Y-m-d");
                        $end_date = date("Y-m-d", strtotime("+3 month", $time));
                    } else {
                        $start_date = date("Y-m-d", strtotime("+1 day", strtotime($getCwo->end_date)));
                        $end_date = date('Y-m-d', strtotime('+3 month', strtotime($getCwo->end_date)));
                    }
                    $type = 1;
                    $amount = 300;
                    
                }
                // if($subscription_detail_id == 'yearly'){
                //     $end_date = date("Y-m-d", strtotime("+1 year", $time));
                //     $type = 2;
                //     $amount = 3420;
                // }
                if($subscription_detail_id == 'yearly'){
                    if($getCwo->end_date == ''){
                        $start_date = date("Y-m-d");
                        $end_date = date("Y-m-d", strtotime("+1 year", $time));
                    } else {
                        $start_date = date("Y-m-d", strtotime("+1 day", strtotime($getCwo->end_date)));
                        $end_date = date('Y-m-d', strtotime('+1 year', strtotime($getCwo->end_date)));
                    }
                    $type = 2;
                    $amount = 3420;
                }
            } elseif($getCwo->free_trial == 1) { // if free trial exists
                if($subscription_detail_id == 'monthly'){
                    if($getCwo->end_date == ''){
                        $start_date = date("Y-m-d");
                        $end_date = date("Y-m-d", strtotime("+1 month", $time));
                    } else {
                        $start_date = date("Y-m-d", strtotime("+1 day", strtotime($getCwo->end_date)));
                        $end_date = date('Y-m-d', strtotime('+1 month', strtotime($getCwo->end_date)));
                    }
                    $type = 1;
                    $amount = 300;
                    
                }
                if($subscription_detail_id == 'quarterly'){
                    if($getCwo->end_date == ''){
                        $start_date = date("Y-m-d");
                        $end_date = date("Y-m-d", strtotime("+3 month", $time));
                    } else {
                        $start_date = date("Y-m-d", strtotime("+1 day", strtotime($getCwo->end_date)));
                        $end_date = date('Y-m-d', strtotime('+3 month', strtotime($getCwo->end_date)));
                    }
                    $type = 1;
                    $amount = 300;
                    
                }
                if($subscription_detail_id == 'yearly'){
                    if($getCwo->end_date == ''){
                        $start_date = date("Y-m-d");
                        $end_date = date("Y-m-d", strtotime("+1 year", $time));
                    } else {
                        $start_date = date("Y-m-d", strtotime("+1 day", strtotime($getCwo->end_date)));
                        $end_date = date('Y-m-d', strtotime('+1 year', strtotime($getCwo->end_date)));
                    }
                    $type = 2;
                    $amount = 3420;
                }
            } else { // if no previous subscription
                if($subscription_detail_id == 'monthly'){
                    $start_date = date("Y-m-d");
                    $end_date = date("Y-m-d", strtotime("+1 month", $time));
                    $type = 1;
                    $amount = 300;
                    
                }
                if($subscription_detail_id == 'quarterly'){
                    $start_date = date("Y-m-d");
                    $end_date = date("Y-m-d", strtotime("+3 month", $time));
                    $type = 1;
                    $amount = 300;
                    
                }
                if($subscription_detail_id == 'yearly'){
                    $start_date = date("Y-m-d");
                    $end_date = date("Y-m-d", strtotime("+1 year", $time));
                    $type = 2;
                    $amount = 3420;
                }
            }
            return response()->json(['message' => '', 'status' => 1, 'start_date' => $start_date, 'end_date' => $end_date, 'type' => $type, 'amount' => $amount], 200);

        } else {
            return response()->json(['message' => 'Please select a package', 'status' => 0], 200);
        }
        // return response()->json(['message' => '', 'status' => 1, 'start_date' => $start_date, 'end_date' => $end_date, 'type' => $type, 'amount' => $amount], 200);
    }

    public function renewInfoPost(Request $request)
    {
        $request->validate([
            'cwo_id' => 'required',
            'start_date' => 'required',
            'end_date' => 'required',
            'type' => 'required',
            'amount' => 'required',
        ]);
        $cwo_id = $request->input('cwo_id');
        $subscription_detail_id = 1;
        $start_date = $request->input('start_date');
        $end_date = $request->input('end_date');
        $type = $request->input('type');
        $amount = $request->input('amount');
        $item = CarWashOwner::findOrFail($cwo_id);
        $subscription_data = [
                'subscription_detail_id' => 1,
                'cwo_id' => $cwo_id,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'type' => $type,
                'amount' => $amount,
                'status' => 1,
            ];
            $subs_create = CwoSubscription::create($subscription_data);

            $cwo_subscription_id = $subs_create['id'];
            $item->update([
                'cwo_subscription_id'=> $cwo_subscription_id,
                'start_date'=> $start_date,
                'end_date'=> $end_date,
                'is_paid'=> 1
                ]);
        // return response()->json(['message' => '', 'status' => 1, 'start_date' => $start_date, 'end_date' => $end_date, 'type' => $type, 'amount' => $amount], 200);
        return redirect()->back()->with('success', 'Subscription has been updated Successfully.');
    }
}
