<?php

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

class Content extends Engine {
  private $engine;
  private $valid;

  public function __construct () {
    $this->engine = new Engine();
    $this->valid = getPerms();
  }

  public function add (Request $r) {
    if ($this->engine->user && ($this->engine->user->perm['blg_addpost'] || $this->engine->user->perm['blg_addpage'])) {
      $err = '';
      $res = '';
      $frm = array(
        'user_id' => $this->engine->user->id,
        'title' => '',
        'slug' => '',
        'public_status' => 0,
        'publish_date' => null,
        'isMenu' => null,
        'isPost' => 1,
        'message' => ''
      );

      if (isset($r->submit)) {
        // 一応修正
        $sav = $r->publish_date;
        if (is_null($r->public_status)) $r->public_status = 0;
        $r->public_status = (int)$r->public_status;

        if ($r->public_status == 1 && is_null($r->publish_date)) $r->public_status = 0;
        else if ($r->public_status != 1 && is_null($r->publish_date)) $r->publish_date = time();

        if (!is_null($r->publish_date)) $r->publish_date = strtotime($r->publish_date);
        else $r->publish_date = time();

        // フォームの値を保存して
        $frm['title'] = $r->title;
        $frm['slug'] = $r->slug;
        $frm['public_status'] = $r->public_status;
        $frm['publish_date'] = $r->publish_date;
        $frm['isMenu'] = (int)!is_null($r->isMenu) && $r->isMenu == 'on';
        $frm['isPost'] = (int)!is_null($r->isPost) && $r->isPost == '1';
        $frm['message'] = $r->message;

        // 件名、文章又はスラッグがなければ、エラーを出て
        $verify = array('件名' => $r->title, 'スラッグ' => $r->slug, '文章' => $r->message);
        $incomplete = array();
        foreach ($verify as $k => $v) { if (is_null($v) || empty($v) || !isset($v)) $incomplete[] = $k; }
        if (count($incomplete) > 0) $err = implode('、', $incomplete).'をご入力下さい。';

        // スラッグが既に存在したら、エラーを出て
        if (empty($err)) {
          $sl = DB::table('blg_content')->select('slug')->where('slug', $r->slug)->first();
          if ($sl && $sl->slug == $r->slug) $err = 'このスラッグがもう存在しています。';
        }

        // エラーがあったら、フォームに戻って。なければ、データベースに保存したり、ページ又はポストへ移転して
        if (!empty($err)) return view('pages.site.content.add', ['res' => $res, 'err' => $err, 'frm' => $frm]);
        else {
          // データベースに追加できるには、値を修正して
          $gs = DB::table('blg_content')->select('sortorder')->orderBy('sortorder', 'desc')->first();
          if (!isset($r->publish_date)) $frm['publish_date'] = ((int)$r->isPost == 1 ? time() : 0);
          if (!isset($r->public_status)) $frm['public_status'] = 0;
          if (!isset($r->isPost)) $frm['isPost'] = 0;
          if (!isset($r->isMenu)) $frm['isMenu'] = 0;
          $frm['isPost'] = (int)$frm['isPost'];
          $frm['isMenu'] = (int)$frm['isMenu'];
          $frm['post_date'] = ((int)$r->isPost == 1 ? time() : 0);
          $frm['sortorder'] = ((int)$r->isPost == 0 ? $gs->sortorder+1 : 0);

          // できたの？
          if ($res = DB::table('blg_content')->insert($frm)) return redirect(($frm['isPost'] == 1 ? '/blog/' : '/').$r->slug);
          else {
            // やれやれ…
            $frm['publish_date'] = $sav;
            unset($frm['post_date']);
            unset($frm['sortorder']);
            return view('pages.site.content.add', ['res' => $res, 'err' => $err, 'frm' => $res['err']]);
          }
        }
      }

      return view('pages.site.content.add', ['res' => $res, 'err' => $err, 'frm' => $frm]);
    }

    return view('pages.site.notallowed');
  }

  public function delete (Request $r) {
    $chk = DB::table('blg_content')->select('isPost')->where('slug', $r->slug)->first();
    if (($this->valid['blg_delpost'] && $chk->isPost == 1) || ($this->valid['blg_delpage'] && $chk->isPost == 0)) {
      if (DB::table('blg_content')->where('slug', $r->slug)->delete()) return redirect('/');
    }

    return view('pages.site.notallowed');
  }

  public function edit (Request $r) {
    if ($this->engine->user && ($this->engine->user->perm['blg_editpost'] || $this->engine->user->perm['blg_editpage'])) {
      $frm = DB::table('blg_content')->where('slug', $r->slug)->first();
      if (!$frm) return view('pages.site.notfound');
      $err = '';
      $res = '';

      if (isset($r->submit)) {
        // 一応修正
        $sav = $r->publish_date;
        if (is_null($r->public_status)) $r->public_status = 0;
        $r->public_status = (int)$r->public_status;

        if ($r->public_status == 1 && is_null($r->publish_date)) $r->public_status = 0;
        else if ($r->public_status != 1 && is_null($r->publish_date)) $r->publish_date = time();

        if (!is_null($r->publish_date)) $r->publish_date = strtotime($r->publish_date);
        else $r->publish_date = time();

        // フォームの値を保存して
        $frm->title = $r->title;
        $frm->public_status = $r->public_status;
        $frm->publish_date = $r->publish_date;
        $frm->isMenu = (int)!is_null($r->isMenu) && $r->isMenu == 'on';
        $frm->isPost = (int)!is_null($r->isPost) && $r->isPost == 'on';
        $frm->message = $r->message;

        // 件名、文章又はスラッグがなければ、エラーを出て
        $verify = array('件名' => $r->title, '文章' => $r->message);
        $incomplete = array();
        foreach ($verify as $k => $v) { if (is_null($v) || empty($v) || !isset($v)) $incomplete[] = $k; }
        if (count($incomplete) > 0) $err = implode('、', $incomplete).'をご入力下さい。';

        // エラーがあったら、フォームに戻って。なければ、データベースに保存したり、ページ又はポストへ移転して
        if (!empty($err)) return view('pages.site.content.edit', ['res' => $res, 'err' => $err, 'frm' => $frm]);
        else {
          // データベースに追加できるには、値を修正して
          $gs = DB::table('blg_content')->select('sortorder')->orderBy('sortorder', 'desc')->first();
          if (!isset($r->publish_date)) $frm->publish_date = ((int)$r->isPost == 1 ? time() : 0);
          if (!isset($r->public_status)) $frm->public_status = 0;
          if (!isset($r->isPost)) $frm->isPost = 0;
          if (!isset($r->isMenu)) $frm->isMenu = 0;
          $frm->isPost = (int)$frm->isPost;
          $frm->isMenu = (int)$frm->isMenu;
          $frm->post_date = ((int)$r->isPost == 1 ? time() : 0);
          $frm->sortorder = ((int)$r->isPost == 0 ? $gs->sortorder+1 : 0);

          // できたの？
          if ($res = DB::table('blg_content')->where('slug', $r->slug)->update((array)$frm)) return redirect(($frm->isPost == 1 ? '/blog/' : '/').$r->slug);
          else {
            // やれやれ…
            $frm->publish_date = $sav;
            unset($frm->post_date);
            unset($frm->sortorder);
            return view('pages.site.content.edit', ['res' => $res, 'err' => $err, 'frm' => $res['err']]);
          }
        }
      }

      return view('pages.site.content.edit', ['res' => $res, 'err' => $err, 'frm' => $frm]);
    }

    return view('pages.site.notallowed');
  }
}