<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PromoCode;
use Illuminate\Support\Facades\Cookie;
use App\Models\PaymentMethod;
use App\Models\Lab;
use Laravel\Socialite\Facades\Socialite;

class MyAccountController extends Controller {

    public function index(Request $request){

        return view('app.my-account.log-in-settings');
    }
    
    public function logInSettings(Request $request){
        return view('app.my-account.log-in-settings');
    }

    public function enableGoogleLogIn(Request $request){
        $request->session()->put('user_uid_to_enable_google_log_in', $this->user->uid);
        return Socialite::driver('google')->redirect();
    }

    public function enableFacebookLogIn(Request $request){
        $request->session()->put('user_uid_to_enable_facebook_log_in', $this->user->uid);
        return Socialite::driver('facebook')->redirect();
    }

    public function searchLab(Request $request){
        $term = $request->input('term') ? trim($request->input('term')) : '';
        if (empty($term)) return '';
        $term = strtolower($term);

        $term2 = '';
        if (strpos($term, ' ') !== FALSE) {
        $terms = explode(' ', $term);
        $term = trim($terms[0]);
        $term2 = trim($terms[1]);
        }
        $labs = Lab::query();


        $labs = $labs->where(function ($q) use ($term) {
            $q->orWhereRaw('LOWER(addresss::text) LIKE ?', ['%' . $term . '%']);
          });
      
          if (!empty($term2)) {
            $labs = $labs->where(function ($q) use ($term2) {
              $q->orWhereRaw('LOWER(addresss::text) LIKE ?', ['%' . $term2 . '%']);
            });
          }


        $labs = $labs->get();

        $labsJson = $labs->map(function ($lab) {
        return [
            "uid" => $lab->uid,
            "id" => $lab->id,
            "text" => $lab->name . ' • ' . $lab->address(true),
        ];
        });
        return json_encode([
        "results" => $labsJson
        ]);
    }
}
