<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Pagename;
use App\Meta;

class BackendMeta extends Controller
{
    public function index(){
      if( config('corepackage.catalog.activate') == 'yes' ){
        $data['pagename'] = Pagename::all();
      }else{
        $data['pagename'] = Pagename::whereNotIn('key',['product'])->get();
      }
      $data['page'] = 'meta';
      return view('backend.meta')->with($data);
    }

    public function get($id){
      $data['id'] = $id;
      $data['pagename'] = Pagename::find($id);
      $title = Pagename::find($id)->meta_tags()->where('name','title')->first();
      $data['title'] = isset($title)?$title->content:"";
      $desc = Pagename::find($id)->meta_tags()->where('name','description')->first();
      $data['desc'] = isset($desc)?$desc->content:"";
      $keyword = Pagename::find($id)->meta_tags()->where('name','keywords')->first();
      $data['keyword'] = isset($keyword)?explode(',',$keyword->content):"";
      return view('backend.meta_list')->with($data);
    }

    public function update(Request $req,$id){
      $title = $req->title;
      $desc = $req->description;
      if($req->keywords){
        $keyword = implode(',',$req->keywords);
      }else{
        $keyword = "";
      }

      $toCheck = array('title','description','keywords');
      foreach ($toCheck as $key => $value) {
        $check = Pagename::find($id)->meta_tags()->where('name',$value)->first();
        if(empty($check)){
          #create
          $db = new Meta;
          $db->pagename_id = $id;
          $db->name = $value;
        }else{
          #update
          $db = Meta::find($check->id);
        }


        if($value == 'title'){
          $db->content = $title;
        }elseif ($value == 'description') {
          $db->content = $desc;
        }else{
          $db->content = $keyword;
        }
        $db->save();
      }
      $req->session()->flash('message', 'Updated successfully!');
      $req->session()->flash('alert-class', 'alert-success');
      $req->session()->flash('pname_id',$id);
      return back();
    }
}
