<?php
namespace App\Helpers;

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\ProfileSekolah;
use App\DataSekolah;
use App\DataGuru;
use App\Blog;
use App\Link;
use App\Banner;
use App\DataFile;
use App\Gallery;
use App\Kegiatan;
use App\Logging;
use App\ManagementSekolah;
use App\Pages;
use App\StrukturOrganisasi;
use App\User;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Image;
use Illuminate\Support\Str;
use Throwable;
use ZipArchive;

class General {
    public static function acakstring($panjang)
    {
        $karakter= '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';

       for ($i = 0; $i < $panjang; $i++) {
          $pos = rand(0, strlen($karakter)-1);
          $string .= $karakter[$pos];
        }
        return $string;
    }

    public static function tgl_indo($tanggal){
        if($tanggal != NULL){
            $tanggal = date('Y-m-d', strtotime($tanggal));
            $bulan = array (
                1 =>   'Januari',
                'Februari',
                'Maret',
                'April',
                'Mei',
                'Juni',
                'Juli',
                'Agustus',
                'September',
                'Oktober',
                'November',
                'Desember'
            );
            $pecahkan = explode('-', $tanggal);

            // variabel pecahkan 0 = tahun
            // variabel pecahkan 1 = bulan
            // variabel pecahkan 2 = tanggal
            // variabel pecahkan 3 = jam

            return $pecahkan[2] . ' ' . $bulan[ (int)$pecahkan[1] ] . ' ' . $pecahkan[0];
        }else{
            return '-';
        }
    }

    public static function full_indo($tanggal){
        if($tanggal != NULL){
            $tanggal = date('Y-m-d-H:i:s', strtotime($tanggal));
            $bulan = array (
                1 =>   'Januari',
                'Februari',
                'Maret',
                'April',
                'Mei',
                'Juni',
                'Juli',
                'Agustus',
                'September',
                'Oktober',
                'November',
                'Desember'
            );
            $pecahkan = explode('-', $tanggal);

            // variabel pecahkan 0 = tahun
            // variabel pecahkan 1 = bulan
            // variabel pecahkan 2 = tanggal
            // variabel pecahkan 3 = jam

            return $pecahkan[2] . ' ' . $bulan[ (int)$pecahkan[1] ] . ' ' . $pecahkan[0] . ' ' .$pecahkan[3];
        }else{
            return '-';
        }
    }

    public static function hari_indo($day)
    {
        $hari = date("D", strtotime($day));

        switch($hari){
            case 'Sun':
                $hari_ini = "Minggu";
            break;

            case 'Mon':
                $hari_ini = "Senin";
            break;

            case 'Tue':
                $hari_ini = "Selasa";
            break;

            case 'Wed':
                $hari_ini = "Rabu";
            break;

            case 'Thu':
                $hari_ini = "Kamis";
            break;

            case 'Fri':
                $hari_ini = "Jumat";
            break;

            case 'Sat':
                $hari_ini = "Sabtu";
            break;

            default:
                $hari_ini = "Tidak di ketahui";
            break;
        }

        return $hari_ini;
    }

    public static function bulan_indo($month)
    {
        $bulan = date("m", strtotime($month));

        switch($bulan){
            case '01':
                $bulan_ini = "Januari";
            break;

            case '02':
                $bulan_ini = "Februari";
            break;

            case '03':
                $bulan_ini = "Maret";
            break;

            case '04':
                $bulan_ini = "April";
            break;

            case '05':
                $bulan_ini = "Mei";
            break;

            case '06':
                $bulan_ini = "Juni";
            break;

            case '07':
                $bulan_ini = "Juli";
            break;

            case '08':
                $bulan_ini = "Agustus";
            break;

            case '09':
                $bulan_ini = "September";
            break;

            case '10':
                $bulan_ini = "Oktober";
            break;

            case '11':
                $bulan_ini = "November";
            break;

            case '12':
                $bulan_ini = "Desember";
            break;

            default:
                $bulan_ini = "Tidak di ketahui";
            break;
        }

        return $bulan_ini;
    }

    public static function idr_format($val) {
    	return "Rp. " . number_format($val,2,',','.');
    }

    public static function log($username, $log) {
        $data = new Logging();
        $data->username = $username;
        $data->log = $log;
        $data->ip_address = \Request::getClientIp(true);
        $data->created_at = Carbon::now('Asia/Jakarta');
        $data->updated_at = null;
        $data->save();
    }

    public static function view_log()
    {
        $data = Logging::from('loggings as a')
                ->leftJoin('dbo.users as b', 'b.username', '=', 'a.username')
                ->select('a.*', 'a.created_at as tgl_log', 'b.foto as foto')
                ->where('a.username', \Auth::user()->username)
                ->limit(5)
                ->get();
        return $data;
    }

    public static function web_config($select)
    {
        $data = ProfileSekolah::select($select)->first();
        return $data->$select;
    }

    public static function kontak_config($select, $sekolah_id)
    {
        $data = DataSekolah::where('sekolah_id', $sekolah_id)->select($select)->first();
        if($data != NULL){
            return $data->$select;
        }else{
            if($select == 'nomor_telepon'){
                return \Helper::web_config('telepon_sekolah');
            }elseif($select == 'email'){
                return \Helper::web_config('email_sekolah');
            }elseif($select == 'alamat_jalan'){
                return \Helper::web_config('alamat_sekolah');
            }elseif($select == 'website'){
                return url('/');
            }
        }
    }

    public static function get_recent_post()
    {
        $data = Blog::where('status', '1')->orderBy('created_at', 'DESC')->limit(2)->get();
        return $data;
    }

    public static function get_link()
    {
        $data = Link::where('status', '1')->orderBy('created_at', 'ASC')->limit(10)->get();
        return $data;
    }

    public static function get_banner()
    {
        $data = Banner::where('status', '1')->orderBy('created_at', 'DESC')->first();
        return $data;
    }

    public static function cropImage($source, $path, $width, $height)
    {
        ini_set('memory_limit', '64M');
        $img = Image::make($source)->crop($width, $height);
        return $img->save($path);
    }

    public static function resizeImage($source, $path, $width, $height)
    {
        ini_set('memory_limit', '64M');
        $img = Image::make($source)->resize($width, $height);
        return $img->save($path);
    }

    public static function resizeImageAR($source, $path, $width, $height)
    {
        ini_set('memory_limit', '64M');
        $img = Image::make($source)->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio();
        });
        return $img->save($path);
    }

    public static function createThumbnail($source, $path, $width, $height)
    {
        ini_set('memory_limit', '64M');
        $img = Image::make($source)->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio();
        });
        return $img->save($path);
    }

    /* Banner Slug */
    public static function createBannerSlug($title, $id = 0)
    {
        $slug = Str::slug($title, '-');
        $allSlugs = \Helper::getRelatedBanner($slug, $id);
        if (!$allSlugs->contains('slug', $slug)) {
            return $slug;
        }

        $i = 1;
        $is_contain = true;
        do {
            $newSlug = $slug . '-' . $i;
            if (!$allSlugs->contains('slug', $newSlug)) {
                $is_contain = false;
                return $newSlug;
            }
            $i++;
        } while ($is_contain);
    }

    protected static function getRelatedBanner($slug, $id = 0)
    {
        return Banner::select('slug')->where('slug', 'like', $slug . '%')
            ->where('id', '<>', $id)
            ->get();
    }
    /* End Banner Slug */

    /* Blog Slug */
    public static function createBlogSlug($title, $id = 0)
    {
        $slug = Str::slug($title, '-');
        $allSlugs = \Helper::getRelatedBlog($slug, $id);
        if (!$allSlugs->contains('slug', $slug)) {
            return $slug;
        }

        $i = 1;
        $is_contain = true;
        do {
            $newSlug = $slug . '-' . $i;
            if (!$allSlugs->contains('slug', $newSlug)) {
                $is_contain = false;
                return $newSlug;
            }
            $i++;
        } while ($is_contain);
    }

    protected static function getRelatedBlog($slug, $id = 0)
    {
        return Blog::select('slug')->where('slug', 'like', $slug . '%')
            ->where('id', '<>', $id)
            ->get();
    }
    /* End Blog Slug */

    /* Kegiatan Slug */
    public static function createKegSlug($title, $id = 0)
    {
        $slug = Str::slug($title, '-');
        $allSlugs = \Helper::getRelatedKeg($slug, $id);
        if (!$allSlugs->contains('slug', $slug)) {
            return $slug;
        }

        $i = 1;
        $is_contain = true;
        do {
            $newSlug = $slug . '-' . $i;
            if (!$allSlugs->contains('slug', $newSlug)) {
                $is_contain = false;
                return $newSlug;
            }
            $i++;
        } while ($is_contain);
    }

    protected static function getRelatedKeg($slug, $id = 0)
    {
        return Kegiatan::select('slug')->where('slug', 'like', $slug . '%')
            ->where('id', '<>', $id)
            ->get();
    }
    /* End Kegiatan Slug */

    /* Pages Slug */
    public static function createPageSlug($title, $id = 0)
    {
        $slug = 'pages/'.Str::slug($title, '-');
        $allSlugs = \Helper::getRelatedPages($slug, $id);
        if (!$allSlugs->contains('slug', $slug)) {
            return $slug;
        }

        $i = 1;
        $is_contain = true;
        do {
            $newSlug = $slug . '-' . $i;
            if (!$allSlugs->contains('slug', $newSlug)) {
                $is_contain = false;
                return $newSlug;
            }
            $i++;
        } while ($is_contain);
    }

    protected static function getRelatedPages($slug, $id = 0)
    {
        return Pages::select('slug')->where('slug', 'like', $slug.'%')
            ->where('id', '<>', $id)
            ->get();
    }
    /* Pages Slug */

    public static function periode()
    {
        $semester = ((Carbon::now('Asia/Jakarta')->format('n') >= 1) AND (Carbon::now('Asia/Jakarta')->format('n') <= 6)) ? 2 : 1;
        $tahun = ($semester == 2) ? date('Y')-1 : date('Y');
        $periode = $tahun.$semester;
        return $periode;
    }

    public static function copy_directory($source, $destination) {
        if ( is_dir( $source ) ) {
            @mkdir( $destination );
            $directory = dir( $source );
            while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
                if ( $readdirectory == '.' || $readdirectory == '..' ) {
                    continue;
                }
                $PathDir = $source . '/' . $readdirectory;
                if ( is_dir( $PathDir ) ) {
                    copy_directory( $PathDir, $destination . '/' . $readdirectory );
                    continue;
                }
                copy( $PathDir, $destination . '/' . $readdirectory );
            }
            $directory->close();
        }else {
            copy( $source, $destination );
        }
    }

    public static function doBackup()
    {
        set_time_limit(0);
        ini_set('memory_limit', '5048M');
        $banners = Banner::get();
        $blogs = Blog::get();
        $files = DataFile::get();
        $gallerys = Gallery::get();
        $kegiatans = Kegiatan::get();
        $logos = ProfileSekolah::get();
        $pages = Pages::get();
        $profiles = User::get();
        $gurus = ManagementSekolah::get();
        $strukturs = StrukturOrganisasi::get();
        $fileArr = array();
        foreach($banners as $key => $val){
            $fileArr[] = $val->picture;
        }
        foreach($blogs as $key => $val){
            $fileArr[] = $val->picture;
        }
        foreach($files as $key => $val){
            $fileArr[] = $val->file;
        }
        foreach($gallerys as $key => $val){
            $fileArr[] = $val->picture;
        }
        foreach($kegiatans as $key => $val){
            $fileArr[] = $val->picture;
        }
        foreach($logos as $key => $val){
            $fileArr[] = $val->logo;
        }
        foreach($pages as $key => $val){
            $fileArr[] = $val->picture;
        }
        foreach($profiles as $key => $val){
            $fileArr[] = $val->foto;
        }
        foreach($gurus as $key => $val){
            $fileArr[] = $val->foto;
        }
        foreach($strukturs as $key => $val){
            $fileArr[] = $val->struktur;
        }
        $zipLink = \Helper::converToZip($fileArr);
        return $zipLink;
    }

    public static function converToZip($fileArr)
    {
        try {
            set_time_limit(0);
            ini_set('memory_limit', '-1');
            ini_set('max_execution_time', '0');
            $zip = new ZipArchive;
            if(!File::isDirectory('assets/backup')){
                File::makeDirectory('assets/backup', 0755, true, true);
            }
            $storage_path = 'assets/backup';
            $zipFileName = $storage_path.'/'.Helper::web_config('npsn').'.zip';
            if ($zip->open(($zipFileName), ZipArchive::CREATE) === true) {
                foreach ($fileArr as $relativName) {
                    if(!empty($relativName)){
                        $bannerName = "assets/files/banner/".$relativName;
                        $blogName = "assets/files/blog/".$relativName;
                        $fileName = "assets/files/file/".$relativName;
                        $galleryName = "assets/files/gallery/".$relativName;
                        $kegiatanName = "assets/files/kegiatan/".$relativName;
                        $logoName = "assets/files/logo/".$relativName;
                        $pageName = "assets/files/pages/".$relativName;
                        $profileName = "assets/files/profile/".$relativName;
                        $guruName = "assets/files/sekolah/".$relativName;
                        $strukturName = "assets/files/struktur/".$relativName;
                        $bannerNameThumb = "assets/files/banner/thumbnail/".$relativName;
                        $blogNameThumb = "assets/files/blog/thumbnail/".$relativName;
                        $galleryNameThumb = "assets/files/gallery/thumbnail/".$relativName;
                        $kegiatanNameThumb = "assets/files/kegiatan/thumbnail/".$relativName;
                        $logoNameThumb = "assets/files/logo/thumbnail/".$relativName;
                        $pageNameThumb = "assets/files/pages/thumbnail/".$relativName;
                        $profileNameThumb = "assets/files/profile/thumbnail/".$relativName;
                        $guruNameThumb = "assets/files/sekolah/thumbnail/".$relativName;
                        $strukturNameThumb = "assets/files/struktur/thumbnail/".$relativName;

                        if(file_exists($bannerName)){
                            $zip->addFile("assets/files/banner/".$relativName, $bannerName);
                        }
                        if(file_exists($bannerNameThumb)){
                            $zip->addFile("assets/files/banner/thumbnail/".$relativName, $bannerNameThumb);
                        }
                        if(file_exists($blogName)){
                            $zip->addFile("assets/files/blog/".$relativName, $blogName);
                        }
                        if(file_exists($blogNameThumb)){
                            $zip->addFile("assets/files/blog/thumbnail/".$relativName, $blogNameThumb);
                        }
                        if(file_exists($fileName)){
                            $zip->addFile("assets/files/file/".$relativName, $fileName);
                        }
                        if(file_exists($galleryName)){
                            $zip->addFile("assets/files/gallery/".$relativName, $galleryName);
                        }
                        if(file_exists($galleryNameThumb)){
                            $zip->addFile("assets/files/gallery/thumbnail/".$relativName, $galleryNameThumb);
                        }
                        if(file_exists($kegiatanName)){
                            $zip->addFile("assets/files/kegiatan/".$relativName, $kegiatanName);
                        }
                        if(file_exists($kegiatanNameThumb)){
                            $zip->addFile("assets/files/kegiatan/thumbnail/".$relativName, $kegiatanNameThumb);
                        }
                        if(file_exists($logoName)){
                            $zip->addFile("assets/files/logo/".$relativName, $logoName);
                        }
                        if(file_exists($logoNameThumb)){
                            $zip->addFile("assets/files/logo/thumbnail/".$relativName, $logoNameThumb);
                        }
                        if(file_exists($pageName)){
                            $zip->addFile("assets/files/pages/".$relativName, $pageName);
                        }
                        if(file_exists($pageNameThumb)){
                            $zip->addFile("assets/files/pages/thumbnail/".$relativName, $pageNameThumb);
                        }
                        if(file_exists($profileName)){
                            $zip->addFile("assets/files/profile/".$relativName, $profileName);
                        }
                        if(file_exists($profileNameThumb)){
                            $zip->addFile("assets/files/profile/thumbnail/".$relativName, $profileNameThumb);
                        }
                        if(file_exists($guruName)){
                            $zip->addFile("assets/files/sekolah/".$relativName, $guruName);
                        }
                        if(file_exists($guruNameThumb)){
                            $zip->addFile("assets/files/sekolah/thumbnail/".$relativName, $guruNameThumb);
                        }
                        if(file_exists($strukturName)){
                            $zip->addFile("assets/files/struktur/".$relativName, $strukturName);
                        }
                        if(file_exists($strukturNameThumb)){
                            $zip->addFile("assets/files/struktur/thumbnail/".$relativName, $strukturNameThumb);
                        }
                    }
                }
                $zip->close();

                if ($zip->open($zipFileName) === true) {
                    Storage::disk('SFTP')->putFileAs('.', $zipFileName, \Helper::web_config('npsn').'.zip');
                }
            }
        } catch(Throwable $e) {
            return response()->json(['code' => Response::HTTP_NO_CONTENT, 'msg' => $e], Response::HTTP_NO_CONTENT);
        }
    }
}
