<?php

namespace App\Repositories\Webprofile;

use App\Models\Webprofile\Autopost;
use App\Repositories\Repository;
use DataTables;

class AutopostRepository extends Repository
{
    protected $model;

    public function __construct(Autopost $model)
    {
        $this->model = $model;
    }

    public function get($with = null, $name = null, $orderBy = null)
    {
        return $this->model
            ->when($with, function ($query) use ($with) {
                return $query->with($with);
            })
            ->when($name, function ($query) use ($name) {
                return $query->where('name', 'ilike', '%'.$name.'%');
            })
            ->when($orderBy, function ($query) use ($orderBy) {
                return $query->orderBy($orderBy[0], $orderBy[1]);
            })
            ->get();
    }

    public function datatable($data)
    {
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($row) {
                $btn = '<a href="'.url('/webprofile/autopost/'.$row->id.'/edit').'" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-warning btn-round btn-sm edit">Edit</a>';

                $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-round btn-sm delete">Delete</a>';

                $btn = $btn.'<br>';

                return $btn;
            })
            ->addColumn('description', function ($row) {
                if ($row->type == 'facebook') {
                    $str = 'FACEBOOK ID => '.$row->key_1.'<br>';
                    $str .= 'FACEBOOK SECRET => '.$row->key_2.'<br>';
                    $str .= 'FACEBOOK GRAPH VERSION => '.$row->key_3.'<br>';
                    $str .= 'FACEBOOK ACCESS TOKEN => '.$row->key_4;
                } elseif ($row->type == 'twitter') {
                    $str = 'TWITTER KEY => '.$row->key_1.'<br>';
                    $str .= 'TWITTER SECRET KEY => '.$row->key_2.'<br>';
                    $str .= 'TWITTER TOKEN => '.$row->key_3.'<br>';
                    $str .= 'TWITTER TOKEN SECRET => '.$row->key_4.'<br>';
                    $str .= 'TWITTER BEARER KEY => '.$row->key_5;
                } elseif ($row->type == 'telegram') {
                    $str = 'API TOKEN => '.$row->key_1.'<br>';
                    $str .= 'BOT USERNAME => '.$row->key_2.'<br>';
                    $str .= 'CHANNEL USERNAME => '.$row->key_3.'<br>';
                    $str .= 'CHANNEL SIGNATURE => '.$row->key_4.'<br>';
                    $str .= 'PROXY => '.$row->key_5;
                } elseif ($row->type == 'alia') {
                    $str = 'URL => '.$row->key_1.'<br>';
                    $str .= 'POSTS => '.$row->key_2.'<br>';
                }

                return $str;
            })
            ->rawColumns(['action', 'description'])
            ->make(true);
    }
}
