<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;

use App\Models\Advertisement;
use Illuminate\Http\Request;
use App\Models\Contact;
use App\Models\ContactWidget;
use App\Models\CmsPage;
use Validator;

class ContactController extends Controller
{

    // public function __construct()
    // {
    //     // $this->middleware('auth')->except('create','CMSPages');
    // }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        # code...
    }

    public function create()
    {
        $data = ContactWidget::first();
        $contact_ads = Advertisement::where('page', 1)->get();

        $adPositions = [];

        for ($position = 1; $position <= 4; $position++) {
            $ad = $contact_ads->where('position', $position)->first();
            $adPositions["ad$position"] = $ad;
        }

        // dd($adPositions);
        // $contact_ads = Advertisement::where('page', 1)->get();
        // dd($ads);
        return view('front.contact_us.create', compact('data','adPositions'));
    }

    public function store(Request $request)
    {
        // dd($request->all());
        $validator = Validator::make($request->all(), [
            'title' => ['required'], 
            'first_name' => ['required'],
            'last_name' => ['required'],
            'country_code' => ['required'],
            'email' => 'required|email',
            'phone' => ['required'],
            'subject' => ['required'],
            'comment' => ['required'],
        ]);
        
        if ($validator->fails()) {
            return redirect()->route('contact-us.create')
                ->withErrors($validator)
                ->withInput();
        }
        
        Contact::create($request->all());

        return redirect()->back()->with('success', 'Message sent successfully!');
    }
   
    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function CMSPages()
    {
        $data = CmsPage::first();
        $cms_ads = Advertisement::where('page', 2)->get();
        // dd($ads);
        $adPositions = [];

        for ($position = 1; $position <= 4; $position++) {
            $ad = $cms_ads->where('position', $position)->first();
            $adPositions["ad$position"] = $ad;
        }
        return view('front.cms_pages.index',compact('data','adPositions'));
    }
}
