<?php

namespace App\Http\Controllers;

use App\Models\FormData;
use App\Models\FormDataBackup;
use App\Models\PrizeWeek;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use DB,Str;

class WebsiteController extends Controller
{
    #Save Form
    public function store(Request $request)
    {
        
        $validator = Validator::make($request->all(), [
            'name' => 'required|min:1',
            'location_status' => 'required',
            'phone' => 'required|min:8|max:13',
            'q_id' => 'required|min:11|max:11|unique:form_data',
        ], [
            'name.required' => 'Name is Required',
            'name.min' => 'Enter a valid name',
            'phone.required' => 'Phone Number is Required',
            'phone.min' => 'Enter a valid phone number',
            'phone.max' => 'Enter a valid phone number',
            'q_id.required' => 'Q-ID is Required',
            'q_id.min' => 'Enter a valid Q-ID',
            'q_id.max' => 'Enter a valid Q-ID',
            'q_id.unique' => 'Q-ID already exists',
        ]);

        if ($validator->fails() || session()->get('location_status')!=$request->location_status) {
            return back()->withInput()->withErrors($validator);
        }

        DB::beginTransaction();
        try {

            do {
                $unique_id ="ASM" . mt_rand( 100000000, 999999999 );
             } while ( DB::table( 'form_data_backups' )->where( 'unique_id', $unique_id )->exists() );
            // $unique_id = "ASM" . floor(time() - 999999999);
            $prize_week_id=Setting::first()->prize_week_id;
            $prize_week=PrizeWeek::find($prize_week_id);

            $form_data = new FormData();
            $form_data->unique_id = $unique_id;
            $form_data->prize_week_id = $prize_week_id;
            $form_data->name = $request->name;
            $form_data->phone = trim($request->phone);
            $form_data->q_id = trim($request->q_id);
            $form_data->email = trim($request->email);

            if ($form_data->save()) {

                $form_data_bak = new FormDataBackup();
                $form_data_bak->unique_id = $unique_id;
                $form_data_bak->prize_week_id = $prize_week_id;
                $form_data_bak->name = $request->name;
                $form_data_bak->phone = trim($request->phone);
                $form_data_bak->q_id = trim($request->q_id);
                $form_data_bak->email = trim($request->email);

                if ($form_data_bak->save()) {
                    DB::commit();
                    return redirect()->back()->with('success', 'Congratulations! You are successfully registered. The draw will be held on '. date('d/m/Y',strtotime($prize_week->prize_date)) .'. Good luck!');
                }
                
            }
            DB::rollback();
            return redirect()->back()->with('error', 'Something went wrong....please try again');
        } catch (\Exception $e) {
            // dd($e->getMessage());
            return redirect()->back()->with('error', 'Something went wrong please try again');
        }
    }

    // check location of user
    public function checkLocation(Request $request) 
    {
        
            $validator = Validator::make($request->all(), [
                'latitude'  => 'required',
                'longitude'  => 'required',
            ]);
    
            if ($validator->fails()){
                $errors = $validator->errors();
                return $this->returnErrorResponse($errors->first());
            }
        
        try{
            $userLatitude = $request->latitude;
            $userLongitude = $request->longitude;

            // Define the distance in kilometers (e.g., 0.05 km for a small radius around the shop)
            $distance = 0.5;
            $nearbyShops = Setting::nearby($userLatitude, $userLongitude, $distance)->first();

            // if ($nearbyShops){
                $location_status=Str::random(10);
                session()->flash('location_status',$location_status);
                return $this->returnResponse('Location Verified',$location_status);
            // }

            return $this->returnErrorResponse();

        }catch(\Exception $e){
            return $this->returnErrorResponse($e->getMessage());
            return $this->returnErrorResponse();
        }
    }

}
