<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;

use App\Models\Banner;
use App\Models\Post;
use App\Models\PostCategory;
use App\Models\PostTag;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Hash;
use App\Models\Newsletter;
use App\Models\LibroReclamaciones;
use App\Models\Service;

use Illuminate\Foundation\Validation\ValidatesRequests;

class FrontendController extends Controller
{
    use ValidatesRequests;
    public function index(Request $request)
    {
        if ($request->user()) {
            return redirect()->route($request->user()->role);
        } else {
            return redirect()->route('login');
        }
    }

    public function home()
    {
        // Elimina la verificación de autenticación aquí
        $posts = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
        $banners = Banner::where('status', 'active')->limit(3)->orderBy('id', 'DESC')->get();
        // return $banner;

        return view('frontend.index')
            ->with('posts', $posts)
            ->with('banners', $banners);
    }

    public function aboutUs()
    {
        return view('frontend.pages.about-us');
    }

    public function contact()
    {
        return view('frontend.pages.contact');
    }


    public function blog()
    {
        $post = Post::query();

        if (! empty($_GET['category'])) {
            $slug = explode(',', $_GET['category']);
            $cat_ids = PostCategory::select('id')->whereIn('slug', $slug)->pluck('id')->toArray();
            $post->whereIn('post_cat_id', $cat_ids);
        }

        if (! empty($_GET['tag'])) {
            $slug = explode(',', $_GET['tag']);
            $tag_ids = PostTag::select('id')->whereIn('slug', $slug)->pluck('id')->toArray();
            $post->whereIn('post_tag_id', $tag_ids);
        }

        if (! empty($_GET['show'])) {
            $post = $post->where('status', 'active')->orderBy('id', 'DESC')->paginate($_GET['show']);
        } else {
            $post = $post->where('status', 'active')->orderBy('id', 'DESC')->paginate(9);
        }

        $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();

        return view('frontend.pages.blog')->with('posts', $post)->with('recent_posts', $rcnt_post);
    }

    public function blogDetail($slug)
    {
        $post = Post::getPostBySlug($slug);
        $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
        // return $post;
        return view('frontend.pages.blog-detail')->with('post', $post)->with('recent_posts', $rcnt_post);
    }

    public function blogSearch(Request $request)
    {
        // return $request->all();
        $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
        $posts = Post::orwhere('title', 'like', '%' . $request->search . '%')
            ->orwhere('quote', 'like', '%' . $request->search . '%')
            ->orwhere('summary', 'like', '%' . $request->search . '%')
            ->orwhere('description', 'like', '%' . $request->search . '%')
            ->orwhere('slug', 'like', '%' . $request->search . '%')
            ->orderBy('id', 'DESC')
            ->paginate(9);

        return view('frontend.pages.blog')->with('posts', $posts)->with('recent_posts', $rcnt_post);
    }

    public function blogFilter(Request $request)
    {
        $data = $request->all();
        // return $data;
        $catURL = '';
        if (! empty($data['category'])) {
            foreach ($data['category'] as $category) {
                if (empty($catURL)) {
                    $catURL .= '&category=' . $category;
                } else {
                    $catURL .= ',' . $category;
                }
            }
        }

        $tagURL = '';
        if (! empty($data['tag'])) {
            foreach ($data['tag'] as $tag) {
                if (empty($tagURL)) {
                    $tagURL .= '&tag=' . $tag;
                } else {
                    $tagURL .= ',' . $tag;
                }
            }
        }
        // return $tagURL;
        // return $catURL;
        return redirect()->route('blog', $catURL . $tagURL);
    }

    public function blogByCategory(Request $request)
    {
        $post = PostCategory::getBlogByCategory($request->slug);
        $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();

        return view('frontend.pages.blog')->with('posts', $post->post)->with('recent_posts', $rcnt_post);
    }

    public function blogByTag(Request $request)
    {
        // dd($request->slug);
        $post = Post::getBlogByTag($request->slug);
        // return $post;
        $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();

        return view('frontend.pages.blog')->with('posts', $post)->with('recent_posts', $rcnt_post);
    }

    // Login
    public function login()
    {
        return view('frontend.pages.login');
    }

    public function loginSubmit(Request $request)
    {
        $data = $request->all();
        if (Auth::attempt(['email' => $data['email'], 'password' => $data['password'], 'status' => 'active'])) {
            Session::put('user', $data['email']);
            session()->flash('success', 'Successfully login');

            return redirect()->route('home');
        } else {
            session()->flash('error', 'Invalid email and password pleas try again!');

            return redirect()->back();
        }
    }

    public function logout()
    {
        Session::forget('user');
        Auth::logout();
        session()->flash('success', 'Logout successfully');

        return back();
    }

    public function register()
    {
        return view('frontend.pages.register');
    }

    public function registerSubmit(Request $request)
    {
        // return $request->all();
        $this->validate($request, [
            'name' => 'string|required|min:2',
            'email' => 'string|required|unique:users,email',
            'password' => 'required|min:6|confirmed',
        ]);
        $data = $request->all();
        // dd($data);
        $check = $this->create($data);
        Session::put('user', $data['email']);
        if ($check) {
            session()->flash('success', 'Successfully registered');

            return redirect()->route('home');
        } else {
            session()->flash('error', 'Please try again!');

            return back();
        }
    }

    public function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'status' => 'active',
        ]);
    }

    // Reset password
    public function showResetForm()
    {
        return view('auth.passwords.old-reset');
    }

    public function subscribe(Request $request)
    {
        if (!Newsletter::isSubscribed($request->email)) {
            Newsletter::subscribePending($request->email);
            if (Newsletter::lastActionSucceeded()) {
                session()->flash('success', 'Subscribed! Please check your email');
                return redirect()->route('home');
            } else {
                $error = Newsletter::getLastError();
                return back()->with('error', 'Something went wrong! please try again. Error: ' . $error);
            }
        } else {
            session()->flash('error', 'Already Subscribed');
            return back();
        }
    }

    public function libroReclamaciones()
    {
        return view('frontend.pages.libro-reclamaciones');
    }
    public function libroReclamacionesSubmit(Request $request)
    {
        $this->validate($request, [
            'fecha' => 'required|date',
            'nombre_y_apellidos' => 'required|string|min:2',
            'direccion' => 'required|string',
            'distrito' => 'required|string',
            'documento_tipo' => 'required|string',
            'documento_numero' => 'required|string',
            'email' => 'required|email',
            'telefono' => 'required|string|min:6',
            'detalle' => 'required|string|min:10',
        ]);

        $data = $request->all();
        LibroReclamaciones::create([
            'fecha' => $data['fecha'],
            'nombre_y_apellidos' => $data['nombre_y_apellidos'],
            'direccion' => $data['direccion'],
            'distrito' => $data['distrito'],
            'documento_tipo' => $data['documento_tipo'],
            'documento_numero' => $data['documento_numero'],
            'email' => $data['email'],
            'telefono' => $data['telefono'],
            'padre_o_madre' => $data['padre_o_madre'] ?? null,
            'producto' => $data['producto'] ?? false,
            'servicio' => $data['servicio'] ?? false,
            'reclamo' => $data['reclamo'] ?? false,
            'queja' => $data['queja'] ?? false,
            'detalle' => $data['detalle'],
        ]);

        session()->flash('success', 'Reclamación registrada exitosamente');
        return redirect()->route('libro-reclamaciones');
    }
    // Servicios
    public function services()
    {
        $services = Service::all();
        return view('frontend.pages.services', compact('services'));
    }
    public function salud()
    {
        return view('frontend.pages.salud');
    }
    public function ingenieria_construccion()
    {
        return view('frontend.pages.ingenieria_construccion');
    }
    public function clinical_care()
    {
        return view('frontend.pages.clinical-care');
    }
    public function cedisan()
    {
        return view('frontend.pages.cedisan');
    }
    public function kidney_care()
    {
        return view('frontend.pages.kidney-care');
    }
    public function hemobalance_care()
    {
        return view('frontend.pages.hemobalance-care');
    }
    public function jrs_meddev()
    {
        return view('frontend.pages.jrs-meddev');
    }
    public function primelab()
    {
        return view('frontend.pages.primelab');
    }
    public function intifarma()
    {
        return view('frontend.pages.intifarma');
    }
    public function pandorafarma()
    {
        return view('frontend.pages.pandorafarma');
    }
    public function tsg_trade()
    {
        return view('frontend.pages.tsg-trade');
    }
    public function privacyPolicy()
    {
        return view('frontend.pages.privacy-policy');
    }
    public function termsAndConditions()
    {
        return view('frontend.pages.terms-and-conditions');
    }
    public function shippingPolicy()
    {
        return view('frontend.pages.shipping-policy');
    }
    public function returnPolicy()
    {
        return view('frontend.pages.return-policy');
    }
    public function paymentPolicy()
    {
        return view('frontend.pages.payment-policy');
    }
    public function cookiePolicy()
    {
        return view('frontend.pages.cookie-policy');
    }
    public function securityPolicy()
    {
        return view('frontend.pages.security-policy');
    }
    public function help()
    {
        return view('frontend.pages.help');
    }
}
