<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Mail\SubscriberMail;
use App\Models\Subscriber;
use Illuminate\Http\Request;

class SubscriberController extends Controller
{
    //
    public function StoreSubscriber(Request $request)
    {
            $validated = $request->validate([
                'email' => 'required|email|unique:subscribers|max:30']);

        // else
        // {
            $token = hash('sha256', time());
            $subscriber = new Subscriber;
            $subscriber->email = $request->email;
            $subscriber->token = $token;
            $subscriber->status = 'Pending';
            // $subscriber->save();

            $subscriber->save() ? 'You have successfully subscribed.' : 'Something went wrong, please try again.';

            // Send email
            $subject = $subscriber->email.' subscribed the newsletter';
            $body = $subscriber->email.' has subscribed the newsletter<br>';
            
            // $message .= $verification_link;

           
            $body .= 'If you received this email by mistake, simply delete it. You will not be subscribed';

            \Mail::to($request->email)->queue(new SubscriberMail($subject,$body));
            \Mail::to('subscribers@realtimebrief.com')->queue(new SubscriberMail($subject,$body));

            // return redirect()->back()->with('success', 'Thanks, please check your inbox to check subscription');
            return response()->json(['success' => 'Thanks, please check your inbox to check subscription!']);
        // }
    }

    public function verify($token,$email)
    {

        // Helpers::read_json();
        
        $subscriber_data = Subscriber::where('token',$token)->where('email',$email)->first();
        if($subscriber_data) 

        
        {
            $subscriber_data->token = '';
            $subscriber_data->status = 'Active';
            $subscriber_data->update();

            return redirect()->back()->with('success', 'You are successfully verified as a subscribe to this system');
        } 
        else 
        {
            return redirect()->route('form');
        }
    }
}
