<?php

namespace App\Http\Controllers;

//use App\Models\Admin;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Hash;
use DB;
use Mail;
class FrontController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


  // Use for show  home page content
   public function showHomePage()
   {
     
      $words = DB::table('words')->select('word')->inRandomOrder()->limit(10)->distinct('word')->get();      
      $ads = DB::table('front_page')->where('id',6)->first();  
      //$total_search_done =DB::table('word_search')->get()->sum("total");    
    $total=0;
    $total_search_done =DB::table('search')->get()->sum("total");
    $search  =DB::table('search')->where('id',1)->where('updated_at',date('Y-m-d'))->count();
     // Don't update
    
    if($search<1)
    {
     $total_search = DB::table('search')->where('id',1)->first();  
      
     $add =rand(1,100);
     $total = $total_search->total; 
     $total = $total+$add;
     DB::table('search')->where('id',1)->update(array('total'=>$total,'updated_at'=>date('Y-m-d')));
    
    }

        
    

      return view('pages.front.home',['word_data'=>$words,'ads'=>$ads,'total_search_done'=>$total_search_done]);
   
   }


  // Use for show  synonmys page content
   public function showSynPage()
   {
     
     // $words = DB::table('words')->inRandomOrder()->limit(10)->distinct()->get();
        $words = DB::table('words')->select('word')->inRandomOrder()->limit(10)->distinct('word')->get();      
     
        $ads = DB::table('front_page')->where('id',6)->first();  
     //   $total_search_done =DB::table('word_search')->get()->sum("total");     
         $total_search_done =DB::table('search')->get()->sum("total");   
      return view('pages.front.synonyms',['word_data'=>$words,'ads'=>$ads,'total_search_done'=>$total_search_done]);
   
   }


  // Use for show  Pronouncation page content
   public function showProPage()
   {
     
      $words = DB::table('words')->inRandomOrder()->limit(10)->distinct()->get();      
        $ads = DB::table('front_page')->where('id',6)->first();      
   // $total_search_done =DB::table('word_search')->get()->sum("total"); 
       $total_search_done =DB::table('search')->get()->sum("total");
      return view('pages.front.pronouncation',['word_data'=>$words,'ads'=>$ads,'total_search_done'=>$total_search_done]);
   
   }


  // Use for show about page content
   public function showAboutPage()
   {
     
      $aboutus =  DB::table('front_page')->where('id',1)->first();
        $ads = DB::table('front_page')->where('id',6)->first();       
      return view('pages.front.about',['aboutus'=>$aboutus,'ads'=>$ads]);
   
   }

  // Use for show dcma copyright page content
  public function showDcmaPage()
   {
     $dcma =  DB::table('front_page')->where('id',2)->first();
      $ads = DB::table('front_page')->where('id',6)->first();           
      return view('pages.front.copyright',['dcma'=>$dcma,'ads'=>$ads]);

   }

// Use for show privacy policy page content
   public function showPrivacyPage()
   {
     $privacy =  DB::table('front_page')->where('id',3)->first();
      $ads = DB::table('front_page')->where('id',6)->first();           
      return view('pages.front.privacy',['privacy'=>$privacy,'ads'=>$ads]);

   }

// Use for show terms and conditions page content
   public function showTermsPage()
   {
     $terms =  DB::table('front_page')->where('id',4)->first();
      $ads = DB::table('front_page')->where('id',6)->first();           
      return view('pages.front.termsconditions',['terms'=>$terms,'ads'=>$ads]);

   }


   // Use for show contact page content
   public function showContactPage()
   {
     
        $ads = DB::table('front_page')->where('id',6)->first();       
      return view('pages.front.contact',['ads'=>$ads]);
   
   }


  // Use for post contact data
   public function postContactData(Request $request)
   {

       $validator = Validator::make($request->all(), [
          'name'          => 'required',
          'email'         => 'required|email',
          'subject' => 'required',
          'message'       => 'required'
      ]);

     
     if ($validator->passes())
     {

           

            
             $to = 'devtechyadda@gmail.com';
             $subject = $request->subject;
             $name = $request->name;
             $email= $request->email;
             $message= $request->message;
             
             $from = "info@technopoint.website";
           
             $maildata = array('name'=>$name,'email'=>$email,'subject'=>$subject,'content'=>$message);
             $data= array('name'=>$request->name,'email'=>$request->email,'subject'=>$request->subject,'message'=>$request->message,'created_at'=>date('Y-m-d H:i:s'));
               DB::table('contact')->insert($data);
                
              Mail::send(['html' => 'pages.sent_mail'], $maildata, function($message) use ($to, $subject,$from,$name) 
              {
            
                 $message->to($to, 'Dictionary Mail')->subject($subject);
                 $message->from($from,'Dictionary');
                  
                 return response()->json(['success'=>'Your message has been sent. Thank you!.']);
   
                
             });
            
              
    }

        return response()->json(['error'=>$validator->errors()]);
      


   }








  // Use for post search word
   public function postSearchWord(Request $request)
   {

       $validator = Validator::make($request->all(), [
          'word_search'          => 'required'
      ]);

     
     if ($validator->passes())
     {
         $word_search = $request->word_search;
        
           // Get Api key
            $api_key = DB::table('front_page')->where('id',5)->first();       
    
        // This curl provides definition, synonmys, pronuncation, syallbes, frequency,
          
         $curl = curl_init();

        curl_setopt_array($curl, [
          CURLOPT_URL => "https://wordsapiv1.p.rapidapi.com/words/".$word_search,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => [
            "x-rapidapi-host: wordsapiv1.p.rapidapi.com",
            "x-rapidapi-key: ".$api_key->api_key.""
          ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
        curl_close($curl);


         // This curl provides rhymes,
               
         $curl2 = curl_init();

        curl_setopt_array($curl2, [
          CURLOPT_URL => "https://wordsapiv1.p.rapidapi.com/words/".$word_search."/rhymes",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => [
            "x-rapidapi-host: wordsapiv1.p.rapidapi.com",
            "x-rapidapi-key: ".$api_key->api_key.""
          ],
        ]);

        $response2 = curl_exec($curl2);
        $err2 = curl_error($curl2);
        $httpcode2 = curl_getinfo($curl2, CURLINFO_HTTP_CODE); 
        curl_close($curl2);




        if ($err) 
        {
          //echo "cURL Error #:" . $err;
           return response(['error'=>$err]);
      
        } 
        else 
        {
          //echo $response;
            $search_word='';
            $frequency='';
            $pronunciation='';
            $syllables='';
            $cnt=0;
            $definitions='';
            $synonyms='';
             
             // Provides definition, synonmys, pronuncation, syallbes, frequency,
       
            $words = json_decode($response,true);
             // Provides rhymes,
       
            $words2 = json_decode($response2,true);
            
            if($httpcode==200)
            {

            $search_word =$words['word'];
            
            if(!empty($words['results']))
            {
            	$totalcnt=count($words['results']);
           
            foreach($words['results'] as $wrd)
            {
                $cnt++;
                //For Definintions
                if($cnt<$totalcnt && $totalcnt>1):
                $definitions.=$wrd['definition'].', ';
                else:
                $definitions.=$wrd['definition'];
                endif;
                //For Synonyms
                if(array_key_exists('synonyms',$wrd))
                {
                $synonyms.=implode(', ',$wrd['synonyms']);
                }
            }
           }
           
          if( !empty($words['pronunciation']['all']))
          {
              $pronunciation= $words['pronunciation']['all'];
            
          } 
          if(!empty($words['syllables']['list']))
          {
            $syllables=" List : ".implode(', ',$words['syllables']['list']);
            
          }

          $i=0;
          $rhymes =array(); 
          if(!empty($words2['rhymes']['all']))
          {
          
            foreach ($words2['rhymes']['all'] as $value) 
             {
			 	 if($i<10)
			 	 {
			 	 
			 	
			 			$rhymes[] =$value;
			 	  
			 	 }
			 	    
			 	  $i++;		
            }		

            $rhymes =implode(", ",$rhymes);

            
          }

          if(!empty($words['frequency']))
          {
             $frequency=$words['frequency'];
           
          }

          
           $tbwordsearch = DB::table('word_search')->where('word',$search_word)->first();
            $total=0;
           if(!empty($tbwordsearch))
           {
              $total = $tbwordsearch->total;
              $total =$total+1;

             DB::table('word_search')->where('word',$search_word)->update(array('total'=>$total));
           }
           else
           {
               DB::table('word_search')->insert(array('word'=>$search_word,'total'=>1));
           }   

          return response()->json(['status'=>200,'word'=>$search_word,'definitions'=>$definitions,'synonyms'=>$synonyms,'Pronunciation'=>$pronunciation,'Syllables'=>$syllables,'Frequency'=>$frequency,'rhymes'=>$rhymes]);
           }else{
            return response()->json(['status'=>201,'message'=>'No words found']);
           }

        }
          
             //return response()->json(['success'=>'Your message has been sent. Thank you!.']);
   
              
    }

        return response()->json(['error'=>$validator->errors()]);
      


   }





// Search result on links




  // Use for post search word
   public function getSearchWordLink(Request $request)
   {

       $validator = Validator::make($request->all(), [
          'word_search'          => 'required'
      ]);

     
     if ($validator->passes())
     {
         $word_search = $request->word_search;
       
         // Get Api key
          $api_key = DB::table('front_page')->where('id',5)->first();       
    
        // This curl provides definition, synonmys, pronuncation, syallbes, frequency,
         $curl = curl_init();

        curl_setopt_array($curl, [
          CURLOPT_URL => "https://wordsapiv1.p.rapidapi.com/words/".$word_search,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => [
            "x-rapidapi-host: wordsapiv1.p.rapidapi.com",
            "x-rapidapi-key: ".$api_key->api_key.""
          ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
        curl_close($curl);


         // This curl provides rhymes,
               
         $curl2 = curl_init();

        curl_setopt_array($curl2, [
          CURLOPT_URL => "https://wordsapiv1.p.rapidapi.com/words/".$word_search."/rhymes",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => [
            "x-rapidapi-host: wordsapiv1.p.rapidapi.com",
            "x-rapidapi-key: ".$api_key->api_key.""
          ],
        ]);

        $response2 = curl_exec($curl2);
        $err2 = curl_error($curl2);
        $httpcode2 = curl_getinfo($curl2, CURLINFO_HTTP_CODE); 
        curl_close($curl2);




        if ($err) 
        {
          //echo "cURL Error #:" . $err;
           return response(['error'=>$err]);
      
        } 
        else 
        {
          //echo $response;
            $search_word='';
            $frequency='';
            $pronunciation='';
            $syllables='';
            $cnt=0;
            $definitions='';
            $synonyms='';
             
             // Provides definition, synonmys, pronuncation, syallbes, frequency,
       
            $words = json_decode($response,true);
             // Provides rhymes,
       
            $words2 = json_decode($response2,true);
            
            if($httpcode==200)
            {

            $search_word =$words['word'];
           if(!empty($words['results']))
            {
            $totalcnt=count($words['results']);
           
            foreach($words['results'] as $wrd)
            {
                $cnt++;
                //For Definintions
                if($cnt<$totalcnt && $totalcnt>1):
                $definitions.=$wrd['definition'].', ';
                else:
                $definitions.=$wrd['definition'];
                endif;
                //For Synonyms
                if(array_key_exists('synonyms',$wrd))
                {
                $synonyms.=implode(', ',$wrd['synonyms']);
                }
            }
           }
           
          if( !empty($words['pronunciation']['all']))
          {
              $pronunciation= $words['pronunciation']['all'];
            
          } 
          if(!empty($words['syllables']['list']))
          {
            $syllables=" List : ".implode(', ',$words['syllables']['list']);
            
          }

          $i=0;
         $rhymes =array();
          if(!empty($words2['rhymes']['all']))
          {

            foreach ($words2['rhymes']['all'] as $value) 
             {
			 	 if($i<10)
			 	 {
			 	 
			 	
			 			$rhymes[] =$value;
			 	  
			 	 }
			 	    
			 	  $i++;		
            }		
            $rhymes =implode(", ",$rhymes);
            
          }

          if(!empty($words['frequency']))
          {
             $frequency=$words['frequency'];
           
          }

          $tbwordsearch = DB::table('word_search')->where('word',$search_word)->first();
            $total=0;
           if(!empty($tbwordsearch))
           {
              $total = $tbwordsearch->total;
              $total =$total+1;

             DB::table('word_search')->where('word',$search_word)->update(array('total'=>$total));
           }
           else
           {
               DB::table('word_search')->insert(array('word'=>$search_word,'total'=>1));
           }

          return response()->json(['status'=>200,'word'=>$search_word,'definitions'=>$definitions,'synonyms'=>$synonyms,'Pronunciation'=>$pronunciation,'Syllables'=>$syllables,'Frequency'=>$frequency,'rhymes'=>$rhymes]);
           }else{
            return response()->json(['status'=>201,'message'=>'No words found']);
           }

        }
          
              
    }

    

   }  


 

}
