<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use DateTime;
use Generator;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Mail\BlastMail;


class MailTemplateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(){
        return view('email.push-blast',['blast_body' => 'a','name' => 'david']);
    }
    public function blast()
    {
        $data['email'] = \DB::table('email_template')->first();
        $data['branch'] = \DB::table('branch')->orderBy('cabang','asc')->get();
        $data['months'] = iterator_to_array($this->getMonths());
        return view('email.blast',$data);
    }

    protected function getMonths(): Generator 
    {
        foreach (range(1, Carbon::MONTHS_PER_YEAR) as $month) {
            $human = DateTime::createFromFormat('!m', $month)->format('F'); 
            yield str_pad($month, 2, 0, STR_PAD_LEFT) .' - '. $human;
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function submitBlast(Request $request)
    {
        try{
            \DB::table('email_template')->update(['blast_subject' => $request->blast_subject,'blast_body' => $request->blast_body]);
            
            $subsMonth = Str::substr($request->id_month, 0,2);
						$id_branch = \DB::table('branch')->where('cabang', $request->id_branch)->value('id');

            if($request->id_branch!=null && $subsMonth!='') {
							$getCustomer = \DB::table('customer')->where('id_branch',$id_branch)->whereMonth('tgl_lahir', $subsMonth)->get();
            } else if ($request->id_branch == null) {
							$getCustomer = \DB::table('customer')->whereMonth('tgl_lahir', $subsMonth)->get();
						} else if ($request->id_branch != null) {
							$getCustomer = \DB::table('customer')->where('id_branch',$id_branch)->get();
						} else {
              $getCustomer = \DB::table('customer')->get();
            }

            foreach($getCustomer as $item){
                if($item->email_verified_at!=null && $item->email!=null && $item->email!=''){
                    $details = [
                        'blast_subject'   => $request->blast_subject,
                        'blast_body'       => $request->blast_body,
                        'name' => $item->nama
                    ];
                    \Mail::to($item->email)->send(new BlastMail($details));
                }
            }
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect('mail-template/blast')->withStatus('Email Blast Berhasil Dikirim');

    }
    
    public function uploadImage(Request $request){
        $fileName=time().'_'.$request->file('file')->getClientOriginalName();
        $uploadPath = 'assets/upload_tinymce/';
        // $path=$request->file('file')->storeAs('uploads', $fileName, 'public');
        $request->file('file')->move($uploadPath,$fileName);
        
        return response()->json(['location'=>public_path().$uploadPath.$fileName]); 
        
        /*$imgpath = request()->file('file')->store('uploads', 'public'); 
        return response()->json(['location' => "/storage/$imgpath"]);*/

    }    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data['email'] = \DB::table('email_template')->first();
        return view('email.template',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if($request->file('welcome_attach')){
            $oldFile = \DB::table('email_template')->first();
            $fileName='member-new.'.$request->file('welcome_attach')->extension();
            $uploadPath = 'assets/picture/';
            if(unlink('assets/picture/'.$oldFile->welcome_attach)){
                if($request->file('welcome_attach')->move($uploadPath,$fileName)){
                    \DB::table('email_template')->update(['welcome_subject' => $request->welcome_subject,'body' => $request->body,'welcome_attach' => $fileName]);
                    return redirect('mail-template/1/edit')->withStatus('Template Email Berhasil Diperbarui');
                }            
            }
        }
        else{
            \DB::table('email_template')->update(['welcome_subject' => $request->welcome_subject,'body' => $request->body]);
            return redirect('mail-template/1/edit')->withStatus('Template Email Berhasil Diperbarui');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
