<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Blog;


// use Excel;

class BlogController extends Controller
{
	public function list($id=null, Request $request)
	{
        $site_id=$id;
        $result = DB::table('blogs')
                  ->join('sites','blogs.site_id','=','sites.id')
                  ->orderBy('blogs.created_at','desc')
                  ->where('blogs.site_id', '=', $site_id)
                  ->get(["sites.site_name","blogs.*"]);
        return view('admin.blog.list', ['site_id' => $site_id, 'result' => $result,  'request' => $request]);
	}

    public function add($id=null, Request $request)
    {
    	// dd($request);
    	$site_id = $id;

        $obj = new Blog;

        if($request->isMethod('POST')){

            $slug_url=$request->blog_slug;
            $data  = DB::table('blogs')
                    ->where(['site_id'=>$site_id])
                    ->where(['slug'=>$slug_url])
                    ->first();
            // dd($data);

            if($data){        
                $blog_id = $data->id;
                // dd($cat_ban_id);
            }else{
                $blog_id = 0;
            }  

            // if ($request->post('blog_image')) {
            //     $image_validation = "mimes:jpeg,jpg,png,webp";
            // } else {
            //     $image_validation = "required|mimes:jpeg,jpg,png,webp";
            // }

            $request->validate([
                'blog_image'=>'nullable|file|mimes:jpeg,jpg,png,webp',
                'blog_slug'=>'required',
                'blog_heading'=>'required',
                'blog_content'=>'required',
                'blog_date'=>'required',
                'blogmeta_title'=>'required',
                'blogmeta_description'=>'required'
                ], [
                    'blog_image.mimes' => 'Please upload a valid image (jpeg, jpg, png, or webp).',
                ]);
            if($blog_id!=0){
                $request->session()->flash('alert-danger', 'Blog already exists.');
            }else{
                if ($request->hasFile('blog_image')) {
                
                    $image = $request->file('blog_image');
                    // $originalName = $image->getClientOriginalName();
                    $originalName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
                    $ext = $image->extension();
                    $image_name = $originalName.'_'.time() . '.' . $ext;
                    $request->blog_image->move(public_path('upload/blog_images'), $image_name);
                }else{
                    $image_name = null;
                }

                if($blog = $obj->create([
                    
                    'slug' => $request->blog_slug,
                    'site_id' => $request->site_id,
                    'blog_heading' => $request->blog_heading,
                    'blog_img' => $image_name,
                    'blog_content' => $request->blog_content, 
                    'post_date' => $request->blog_date,
                    'meta_title' => $request->blogmeta_title, 
                    'meta_description' => $request->blogmeta_description, 

                ]))
              
                {
                    $request->session()->flash('alert-success', 'Blog successfully added.');
                    return redirect()->route('admin.blog.list', ['id' => $site_id]);
                }else{
                    $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                    return redirect()->back()->with($request->except(['_method', '_token']));
                }
            }

        }
        return view('admin.blog.add', ['site_id' => $site_id, 'request' => $request]);
    }


	public function edit($id = null, Request $request)
    {
    	$blog_id = $id;
        $dataDetails  = Blog::where('id',$blog_id)->first();
        $siteId = $dataDetails->site_id;
        
        $obj = new Blog;
         
        if($request->isMethod('POST')){

            $request->validate([
                'blog_image'=>'nullable|file|mimes:jpeg,jpg,png,webp',
                'blog_slug'=>'required',
                'blog_date'=>'required',
                'blog_heading'=>'required',
                'blog_content'=>'required',
                'blogmeta_title'=>'required',
                'blogmeta_description'=>'required'
            ],[
                'blog_image.mimes' => 'Please upload a valid image (jpeg, jpg, png, or webp).',
            ]);

            $formid = $request->formid;
            $site_id = $request->site_id;

            if ($request->hasFile('blog_image')) {
            
                $image = $request->file('blog_image');
                $originalName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
                $ext = $image->extension();
                $image_name = $originalName.'_'.time() . '.' . $ext;
                $request->blog_image->move(public_path('upload/blog_images'), $image_name);

                if ($dataDetails->blog_img && file_exists(public_path('upload/blog_images/' . $dataDetails->blog_img))) {
                    unlink(public_path('upload/blog_images/' . $dataDetails->blog_img));
                }

            }else{
                $image_name = $request->old_blog_image;
            }

            $update_arr['site_id'] = $request->site_id;
            $update_arr['slug'] = $request->blog_slug;
            $update_arr['blog_heading'] = $request->blog_heading;
            $update_arr['blog_content'] = $request->blog_content;
            $update_arr['post_date'] = $request->blog_date;
            $update_arr['blog_img'] = $image_name;
            $update_arr['meta_title'] = $request->blogmeta_title;
            $update_arr['meta_description'] = $request->blogmeta_description;
            $update_arr['updated_at'] = date('Y-m-d H:i:s');
            
            if(Blog::where(['id' => $request->formid])->update($update_arr)){
                $request->session()->flash('alert-success', 'Blog successfully updated.');
                return redirect()->route('admin.blog.list', ['id' => $site_id]);
            }else{
                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back()->with($request->except(['_method', '_token']));
            }
        }
        return view('admin.blog.edit', ['dataDetails' => $dataDetails, 'request' => $request, 'siteId' => $siteId]);
    }

    public function delete($id = null, Request $request){
        // dd($id);
        $blog_id = decrypt($id);

        $Blog = Blog::find($blog_id);
        $site_id=$Blog->site_id;
        
        if (!$Blog) {
            $request->session()->flash('alert-danger', 'No data found for this id!');
        }

        if ($Blog->blog_img && file_exists(public_path('upload/blog_images/' . $Blog->blog_img))) {
            unlink(public_path('upload/blog_images/' . $Blog->blog_img));
        }

        $Blog->delete();

        $request->session()->flash('alert-danger', 'Blog successfully delete.');
        return redirect()->route('admin.blog.list', ['id' => $site_id]);
    }

    public function status(Request $request)
    {
        if($request->id == null || $request->status == null){
            // return redirect()->route('admin.category.list');
        }
        $id = base64_decode($request->id);
        switch($request->status){
            case 'N':
                $block = 'Y';
                $blockText = 'Block';
                break;
            case 'Y':
                $block = 'N';
                $blockText = 'Unblock';
                break;
            default:
                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back();
        }

        if(Blog::where(['id' => $id])->update(['is_block' => $block])){
            $prompt = array('status' => 1, 'id' => $id, 'event' => $blockText);
            echo json_encode($prompt);
        }else{
            $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
            return redirect()->back();
        }
    }

}