<?php

namespace App\Http\Controllers\Home;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Log;

class Comment {
  public function add (Request $r) {
    if (!isset($r->submit)) return redirect('/');
    $isvideo = false;
    if (!$cont = DB::table('blg_content')->where('slug', $r->slug)->first()) { if ($cont = DB::table('vid_video')->where('vid', $r->slug)->first()) $isvideo = true; }

    $user = null;
    if (isset($_COOKIE['kero_token'])) $user = DB::table('users')->select('id')->where('kero_token', $_COOKIE['kero_token'])->first()->id;
    if ($user == 0 && (str_contains($r->newmessage, 'http://') || str_contains($r->newmessage, 'https://'))) return redirect('/');

    $add = DB::table('blg_comments')->insertGetId([
      'user_id' => $user,
      'post_id' => (!$isvideo ? $cont->id : 0),
      'video_id' => ($isvideo ? $r->slug : ''),
      'name' => (isset($r->newname) ? $r->newname : null),
      'email' => (isset($r->newmail) ? $r->newmail : null),
      'message' => $r->newmessage,
      'created' => time()
    ]);

    // 返事だったら、メールを送って
    return redirect('/'.($isvideo ? 'video/play' : 'blog').'/'.$r->slug.'#comment-'.$add);
  }
}