<?php

namespace App\Http\Controllers\Webprofile\Backend;

use App\Http\Controllers\Controller;
use App\Models\Webprofile\Categories;
use App\Repositories\Webprofile\AutopostRepository;
use App\Repositories\Webprofile\De\PostRepository as DePostRepository;
use App\Repositories\Webprofile\En\PostRepository as EnPostRepository;
use App\Repositories\Webprofile\PostRepository;
use App\Repositories\Webprofile\Sa\PostRepository as SaPostRepository;
use App\Repositories\Webprofile\SocialSharingRepository;
use App\Repositories\Webprofile\Zh\PostRepository as ZhPostRepository;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Statickidz\GoogleTranslate;

class PostController extends Controller
{
    private $repo;
    private $repoEn;
    private $repoDe;
    private $repoSa;
    private $repoZh;

    private $SOURCE = 'id';
    private $TARGET = 'en';
    private $TARGETDE = 'de';
    private $TARGETSA = 'ar';
    private $TARGETZH = 'zh';

    public function __construct(
        PostRepository $repo,
        EnPostRepository $repoEn,
        DePostRepository $repoDe,
        SaPostRepository $repoSa,
        ZhPostRepository $repoZh,
        SocialSharingRepository $socialRepo,
        AutopostRepository $autoPostRepo
    ) {
        $this->repo = $repo;
        $this->repoEn = $repoEn;
        $this->socialRepo = $socialRepo;
        $this->autoPostRepo = $autoPostRepo;
        $this->repoDe = $repoDe;
        $this->repoSa = $repoSa;
        $this->repoZh = $repoZh;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = $this->repo->get(['rEn']);

            return $this->repo->datatable($data);
        }

        return view('webprofile.backend.posts.index')->withTitle(trans('feature.post'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Categories::pluck('name', 'id');

        $data = [
            'categories' => $categories,
        ];

        return view('webprofile.backend.posts.create', $data)->withTitle(trans('feature.create_post'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request['content'] = strip_tags($request->content, ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        $request['title'] = strip_tags($request->title);
        $request->validate([
            'title' => 'required',
            'categories' => 'required',
            'content' => 'required|min:3',
            'post_date' => 'required',
            'keys' => 'max:100',
            'thumbnail' => 'mimes:jpg,jpeg,png|max : 3072'

        ], [
            'title.required' => 'Judul wajib diisi',
            'categories.required' => 'Kategori wajib diisi',
            'content.required' => 'Konten wajib diisi',
            'content.min' => 'Konten terlalu singkat',
            'post_date.required' => 'Tanggal posting wajib diisi',
            'keys.max' => 'Keyword terlalu panjang'
        ]);

        $data = $request->except('_token');
        // $data['content'] = htmlspecialchars($request->content);

        array_key_exists('post_status', $data) ? $data['post_status'] = 1 : $data['post_status'] = 0;
        array_key_exists('cover_status', $data) ? $data['cover_status'] = 1 : $data['cover_status'] = 0;
        $data['slug'] = Str::slug($request->input('title'));

        $save = $this->repo->store($data);

        $tipe = 'thumbnail';
        if ($request->hasFile($tipe)) {
            $img[$tipe] = $save->id.'.'.$request->file($tipe)->guessClientExtension();

            $this->repo->upload($img[$tipe], $request, $tipe);
            $this->repo->update($img, $save);
        }

        if (webprofilesetting()['auto_translate'] == 1) {
            // save translate
            if (strlen($data['content']) < 5000) {
                $this->createEn($data, $save);
                $this->createDe($data, $save);
                $this->createSa($data, $save);
                $this->createZh($data, $save);
            }
        }

        $this->share($data, $request);

        return redirect()->route('posts.index');
    }

    public function shorterUrl($long_url)
    {
        $client = new Client();
        $URI = 'http://unesa.me/create.php';
        $params['form_params'] = ['token' => env('TOKEN_URL', 'forge'), 'url_value' => $long_url];
        $response = $client->post($URI, $params);
        $responseJson = json_decode($response->getBody(), true);

        $url = $responseJson['url'];

        return $url;
    }

    public function share($data, $request)
    {

        $client = new Client([
            'headers' => [
                'Accept' => 'application/json',
                // 'Authorization' => 'Bearer ' . session('token')
            ],
            'form_params' => ['url' => url('post/'.$data['slug'])]
        ]);
        $result1      = $client->post('https://alia.unesa.ac.id/api/posts');
        $value  = json_decode($result1->getBody()->getContents(), true);

        // $setting = webprofilesetting();
        // $autoPost = $this->autoPostRepo->get();

        // if ($request->hasFile('thumbnail')) {
        //     $img = $request->file('thumbnail')->getRealPath();
        // } else {
        //     $img = null;
        // }
        // $title = html_entity_decode($data['title']);
        // $url = $this->shorterUrl(url('post/'.$data['slug']));
        // $keys = $data['keys'];

        // $olhashtag = explode(', ', str_replace([', ', ','], ', ', $keys));

        // $hashtag = '#unesa #unesaterkini ';
        // foreach ($olhashtag as $value) {
        //     $hashtag .= '#'.trim($value).' ';
        // }
        // dd($autoPost);

        // foreach ($autoPost as $value) {
            //Social Share Facebook
            // Config::set('larasap.facebook', [
            //     'app_id' => $setting['facebook_app_id'],
            //     'app_secret' => $setting['facebook_app_secret'],
            //     'default_graph_version' => null,
            //     'page_access_token' => null,
            // ]);

            // $this->socialRepo->sendLinkToFacebook(url('post/'.$data['slug']), $data['content']);

            // if ($value->type == 'twitter') {
            //     //Social Share Twitter
            //     Config::set('larasap.twitter', [
            //         'consurmer_key' => $value->key_1,
            //         'consurmer_secret' => $value->key_2,
            //         'access_token' => $value->key_3,
            //         'access_token_secret' => $value->key_4,
            //     ]);

            //     if ($img == '') {
            //         $this->socialRepo->sendTextTweet($setting['header_admin'].'-'.$title."\n\n".$url."\n\n".$hashtag);
            //     } else {
            //         $this->socialRepo->sendTweetWithMedia($setting['header_admin'].'-'.$title."\n\n".$url."\n\n".$hashtag, [$img]);
            //     }
            // }
        // }
    }

    private function createEn($data, $post)
    {
        $trans = new GoogleTranslate();
        $title = $trans->translate($this->SOURCE, $this->TARGET, strip_tags($data['title']));

        if ($data['content'] == null) {
            $data['content'] = 'kosong';
        }

        $content = $trans->translate($this->SOURCE, $this->TARGET, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));

        $dataEn['post_id'] = $post->id;
        $dataEn['title'] = $title;
        $dataEn['content'] = $content;

        $this->repoEn->store($dataEn);
    }

    private function createDe($data, $post)
    {
        $trans = new GoogleTranslate();
        $title = $trans->translate($this->SOURCE, $this->TARGETDE, strip_tags($data['title']));

        if ($data['content'] == null) {
            $data['content'] = 'kosong';
        }

        $content = $trans->translate($this->SOURCE, $this->TARGETDE, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));

        $dataDe['post_id'] = $post->id;
        $dataDe['title'] = $title;
        $dataDe['content'] = $content;

        $this->repoDe->store($dataDe);
    }

    private function createSa($data, $post)
    {
        $trans = new GoogleTranslate();
        $title = $trans->translate($this->SOURCE, $this->TARGETSA, strip_tags($data['title']));

        if ($data['content'] == null) {
            $data['content'] = 'kosong';
        }

        $content = $trans->translate($this->SOURCE, $this->TARGETSA, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));

        $dataSa['post_id'] = $post->id;
        $dataSa['title'] = $title;
        $dataSa['content'] = $content;

        $this->repoSa->store($dataSa);
    }

    private function createZh($data, $post)
    {
        $trans = new GoogleTranslate();
        $title = $trans->translate($this->SOURCE, $this->TARGETZH, strip_tags($data['title']));

        if ($data['content'] == null) {
            $data['content'] = 'kosong';
        }

        $content = $trans->translate($this->SOURCE, $this->TARGETZH, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section','span']));

        $dataZh['post_id'] = $post->id;
        $dataZh['title'] = $title;
        $dataZh['content'] = $content;

        $this->repoZh->store($dataZh);
    }

    /**
     * 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)
    {
        $setting = webprofilesetting();
        $data = $this->repo->findId($id, ['rEn', 'rDe', 'rSa', 'rZh']);
        $categories = Categories::pluck('name', 'id');
        $manual=0;

        $data = [
            'data' => $data,
            'categories' => $categories,
            'setting' => $setting,
            'manual'=> $manual,
        ];

        return view('webprofile.backend.posts.edit', $data)->withTitle(trans('feature.edit_post'));
    }
    public function editPerBahasa($id)
    {
        $setting = webprofilesetting();
        $data = $this->repo->findId($id, ['rEn', 'rDe', 'rSa', 'rZh']);
        $categories = Categories::pluck('name', 'id');
        $manual=1;

        $data = [
            'data' => $data,
            'categories' => $categories,
            'setting' => $setting,
            'manual' => $manual,
        ];

        return view('webprofile.backend.posts.edit_per_bahasa', $data)->withTitle(trans('feature.edit_post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request['content'] = strip_tags($request->content, ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        $request['content_en'] = strip_tags($request->content_en, ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        $request['content_de'] = strip_tags($request->content_de, ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        $request['content_sa'] = strip_tags($request->content_sa, ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        $request['content_zh'] = strip_tags($request->content_zh, ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        $request['title']  = strip_tags($request->title);
        $request['title_en']  = strip_tags($request->title_en);
        $request['title_de']  = strip_tags($request->title_de);
        $request['title_sa']  = strip_tags($request->title_sa);
        $request['title_zh']  = strip_tags($request->title_zh);

        $request->validate([
            'categories' => 'required',
            'content' => 'required|min:3',
            'post_date' => 'required',
            'keys' => 'max:100',
            'thumbnail' => 'mimes:jpg,jpeg,png|max : 3072'
        ], [
            'categories.required' => 'Kategori wajib diisi',
            'content.required' => 'Konten wajib diisi',
            'content.min' => 'Konten terlalu singkat',
            'post_date.required' => 'Tanggal posting wajib diisi',
            'keys.max' => 'Keyword terlalu panjang'
        ]);


        $data = $request->except(['_token','manual',  'id', 'title_en', 'content_en', 'title_de', 'content_de', 'title_sa', 'content_sa', 'title_zh', 'content_zh']);
        $dataEn = $request->except(['_token', 'id', 'manual']);
        // $data['title'] = htmlspecialchars($request->title);
        // $data['content'] = htmlspecialchars($request->content);

        // $dataEn = $request->except(['_token', 'id', 'manual', 'title_en', 'content_en','title_de', 'content_de', 'title_sa', 'content_sa', 'title_zh', 'content_zh']);
        // $dataEn['title'] = htmlspecialchars($request->title);
        // $dataEn['title_en'] = htmlspecialchars($request->title_en);
        // $dataEn['title_de'] = htmlspecialchars($request->title_de);
        // $dataEn['title_sa'] = htmlspecialchars($request->title_sa);
        // $dataEn['title_zh'] = htmlspecialchars($request->title_zh);
        // $dataEn['content'] = htmlspecialchars($request->content);
        // $dataEn['content_en'] = htmlspecialchars($request->content_en);
        // $dataEn['content_de'] = htmlspecialchars($request->content_de);
        // $dataEn['content_sa'] = htmlspecialchars($request->content_sa);
        // $dataEn['content_zh'] = htmlspecialchars($request->content_zh);

        array_key_exists('post_status', $data) ? $data['post_status'] = 1 : $data['post_status'] = 0;
        array_key_exists('cover_status', $data) ? $data['cover_status'] = 1 : $data['cover_status'] = 0;
        $data['slug'] = Str::slug($request->input('title'));

        $post = $this->repo->findId($id, ['rEn', 'rDe', 'rSa', 'rZh']);
        $edit = $this->repo->update($data, $post);

        $tipe = 'thumbnail';
        if ($request->hasFile($tipe)) {
            $img[$tipe] = $post->id.'.'.$request->file($tipe)->guessClientExtension();

            $this->repo->upload($img[$tipe], $request, $tipe);
            $this->repo->update($img, $post);
        }

        $this->updateEn($dataEn, $post, $request->manual);
        $this->updateDe($dataEn, $post, $request->manual);
        $this->updateSa($dataEn, $post, $request->manual);
        $this->updateZh($dataEn, $post, $request->manual);

        return redirect()->route('posts.index');
    }

    public function updateEn($data, $post, $manual)
    {
        if($manual==1){
            $dataEn['title'] = strip_tags($data['title_en']);
            $dataEn['content'] = strip_tags($data['content_en'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        }
        else{

            if ($data['content'] == null) {
                $data['content'] = 'kosong';
            }

        $trans = new GoogleTranslate();
        $title = $trans->translate($this->SOURCE, $this->TARGET, strip_tags($data['title']));
        if (strlen($data['content']) < 5000) {
        $content = $trans->translate($this->SOURCE, $this->TARGET, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));
        $dataEn['content'] = $content;
        }
        $dataEn['title'] = $title;
    }
        $this->repoEn->update($dataEn, $post);
    }

    public function updateDe($data, $post, $manual)
    {
        if($manual==1){
            $dataDe['title'] = strip_tags($data['title_de']);
            $dataDe['content'] = strip_tags($data['content_de'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        }
        else{

            if ($data['content'] == null) {
                $data['content'] = 'kosong';
            }

            $trans = new GoogleTranslate();
            $title = $trans->translate($this->SOURCE, $this->TARGETDE, strip_tags($data['title']));
            if (strlen($data['content']) < 5000) {
            $content = $trans->translate($this->SOURCE, $this->TARGETDE, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));
            $dataDe['content'] = $content;
            }
            $dataDe['title'] = $title;
        }
        $this->repoDe->update($dataDe, $post);
    }

    public function updateSa($data, $post, $manual)
    {
        if($manual==1){
            $dataSa['title'] = strip_tags($data['title_sa']);
            $dataSa['content'] = strip_tags($data['content_sa'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        }
        else{

            if ($data['content'] == null) {
                $data['content'] = 'kosong';
            }

            $trans = new GoogleTranslate();
            $title = $trans->translate($this->SOURCE, $this->TARGETSA, strip_tags($data['title']));
            if (strlen($data['content']) < 5000) {
            $content = $trans->translate($this->SOURCE, $this->TARGETSA, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));
            $dataSa['content'] = $content;
            }
            $dataSa['title'] = $title;
        }
        $this->repoSa->update($dataSa, $post);
    }

    public function updateZh($data, $post, $manual)
    {
        if($manual==1){
            $dataZh['title'] = strip_tags($data['title_zh']);
            $dataZh['content'] = strip_tags($data['content_zh'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']);
        }
        else{
            if ($data['content'] == null) {
                $data['content'] = 'kosong';
            }

            $trans = new GoogleTranslate();
            $title = $trans->translate($this->SOURCE, $this->TARGETZH, strip_tags($data['title']));
            if (strlen($data['content']) < 5000) {
            $content = $trans->translate($this->SOURCE, $this->TARGETZH, strip_tags($data['content'], ['a', 'br', 'p', 'b', 'i', 'u', 'ul', 'li', 'ol', 'img', 'table', 'tr', 'td', 'th', 'iframe','section', 'span']));
            $dataZh['content'] = $content;
            }
            $dataZh['title'] = $title;
        }
        $this->repoZh->update($dataZh, $post);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = $this->repo->findId($id, ['rEn', 'rDe', 'rSa', 'rZh']);
        $this->repo->destroy($data, 'thumbnail');
        $this->repo->deletefile($data, 'thumbnail');

        if ($data->rEn) {
            $this->repoEn->destroy($data->rEn);
        }

        if ($data->rDe) {
            $this->repoDe->destroy($data->rDe);
        }

        if ($data->rSa) {
            $this->repoSa->destroy($data->rSa);
        }

        if ($data->rZh) {
            $this->repoZh->destroy($data->rZh);
        }

        return response()->json(['done']);
    }
}