<?php

namespace App\Http\Controllers\Marketing;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
use App\Imports\MarketImport;
use App\Models\BusinessCategory;
use App\Models\CompanyAddress;
use App\Models\Marketing;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class MarketingController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:marketing-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Marketing::select([
            'id',
            'name',
            'business_name',
            'gbp_link',
            'rating',
            'total_review',
            'address',
            'website',
            'phone_number',
            'email',
            'claim_status',
            'optimization_score',
            'local_ads',
            'paid_ads',
            'google_ranking',
            'pack_ranking',
            'ai_suggested_services',
            'note',
            'tags',
            'business_category_id',
            'status',
            ])
            ->with('getBusinessCategory')
            ->orderBy('id', 'desc');
        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('business_name', 'like', '%'.$search_query.'%')
                                ->orWhere('phone_number', 'like', '%'.$search_query.'%');
                        })
                        ->paginate($sort_by);

            return view('marketings.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('marketings.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $business = BusinessCategory::select('id','name')->where('status', 1)->get();
        $company_id         = \Auth::user()->company_id ?? '';
        $company_address    = CompanyAddress::select(
            'countries.code as country_code',
            'companies_addresses.country_id',
            'companies_addresses.state_id',
            'companies_addresses.city_id',
        )
        ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
        ->leftjoin('countries', 'countries.id', 'companies_addresses.country_id')
        ->where('companies_addresses.company_id', $company_id)
        ->orWhere('companies.is_default', '1')
        ->first();
        $countryCode   = $company_address->country_code ?? 'us';
        return view('marketings.create',compact('business', 'company_address','countryCode'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd('store');
        $validator = \Validator::make($request->all(), [
            'business_name' => 'required',
            'gbp_link'      => 'unique:marketings,gbp_link',
            'address'       => 'required',
            'phone_number'  => 'required',
            'email'         => 'required|email',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $market = Marketing::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Marketing created successfully',
                'data'    => $market
            ]);
        }

        return redirect()->route('marketings.index')
            ->with('success','Marketing created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $market          = Marketing::find($id);
        $business        = BusinessCategory::select('id','name')->where('status', 1)->get();
        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $country_code->country_code ?? 'us';

        return view('marketings.edit',compact('business', 'company_address','countryCode','market'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd('test');
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            // 'business_name' => 'required',
            'gbp_link'      => 'unique:marketings,gbp_link,' . $id,
            'address'       => 'required',
            'phone_number'  => 'required',
            'email'         => 'required|email'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $marketig = Marketing::find($id);

        if (!$marketig) {
            return redirect()->route('marketing.index')
                ->with('error','Marketing not found!');
        }

        $marketig->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Marketing updated successfully',
                'data'    => $marketig
            ]);
        }

        return redirect()->route('marketing.index')
            ->with('success','Marketing updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = Marketing::find($request->id);

        if ($data->default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        $Redirect = 'marketings';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = Marketing::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Marketing status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function marketCreate(Request $request)
    {
        $business = BusinessCategory::select('id','name')->where('status', 1)->get();
        return view('marketing.import',compact('business'));
    }
    public function marketImport(Request $request)
    {
        $data = \Session::get('market_import') ?? [];

        $data['successImport'] = 0;
        $data['errorImport'] = 0;

        \Session::put('market_import', $data);

        $collection = Excel::import(new MarketImport($request), $request->file('market_import'));
        $data = \Session::get('market_import') ?? [];

        $message = 'File uploaded successfully. ' . $data['successImport'] . ' New Records added, ' . $data['errorImport'] . ' Records already exist.';

        return redirect()->back()->with('success', $message);
    }

    public function downloadSampleFile()
    {
        $filePath = public_path('public/sample_marketing_list.xlsx');
        $headers = [
            'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // Excel MIME type
        ];

        return Response::download($filePath, 'sample_marketing_list.xlsx', $headers);

    }
}
