<?php

namespace App\Http\Controllers;

use App\Models\Language;
use App\Models\User;
use App\Models\User\Language as UserLanguage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Session;

class UpdateController extends Controller
{
    public function version()
    {
        return view('updater.version');
    }

    public function recurse_copy($src, $dst)
    {
        // dd(base_path($src), base_path($dst));
        $dir = opendir(base_path($src));
        @mkdir(base_path($dst), 0775, true);
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir(base_path($src) . '/' . $file)) {
                    $this->recurse_copy($src . '/' . $file, $dst . '/' . $file);
                } else {
                    copy(base_path($src . '/' . $file), base_path($dst) . '/' . $file);
                }
            }
        }
        closedir($dir);
    }

    public function upversion(Request $request)
    {

        $assets = array(
            ['path' => 'app', 'type' => 'folder', 'action' => 'replace'],
            ['path' => 'config', 'type' => 'folder', 'action' => 'replace'],
            ['path' => 'database/migrations', 'type' => 'folder', 'action' => 'add'],
            ['path' => 'resources/views', 'type' => 'folder', 'action' => 'replace'],
            ['path' => 'routes', 'type' => 'folder', 'action' => 'replace'],
            ['path' => 'version.json', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'composer.json', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'composer.lock', 'type' => 'file', 'action' => 'replace'],

            // ['path' => 'assets/front/user/css/style.css', 'type' => 'file', 'action' => 'replace'],
            // ['path' => 'assets/front/user/css/common.css', 'type' => 'file', 'action' => 'replace'],
            // ['path' => 'assets/front/user/js/theme9/main.js', 'type' => 'file', 'action' => 'replace'],

            ['path' => 'assets/admin/js/custom.js', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/css/common-rtl.css', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/css/common.css', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/css/style.css', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/css/theme45.css', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/js/main.js', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/js/theme12/main.js', 'type' => 'file', 'action' => 'replace'],
            ['path' => 'assets/front/user/js/theme12/rtl-main.js', 'type' => 'file', 'action' => 'replace'],


            ['path' => 'assets/front/img/user/templates', 'type' => 'folder', 'action' => 'replace'],
            ['path' => 'assets/front/img/themes', 'type' => 'folder', 'action' => 'replace'],



            ['path' => 'assets/front/user/css/theme4-5/custom-dev.css', 'type' => 'file', 'action' => 'add'],
            ['path' => 'assets/user/js/edit-image-modal.js', 'type' => 'file', 'action' => 'add'],
            ['path' => 'assets/user/js/gallery.js', 'type' => 'file', 'action' => 'add'],
            ['path' => 'assets/user/js/post.js', 'type' => 'file', 'action' => 'add'],
            ['path' => 'assets/user/js/rtl.js', 'type' => 'file', 'action' => 'add'],

            ['path' => 'assets/front/user/css/theme13', 'type' => 'folder', 'action' => 'add'],
            ['path' => 'assets/front/user/css/theme14', 'type' => 'folder', 'action' => 'add'],
            ['path' => 'assets/front/user/js/theme13', 'type' => 'folder', 'action' => 'add'],
            ['path' => 'assets/front/user/js/theme14', 'type' => 'folder', 'action' => 'add'],


        );
        foreach ($assets as $key => $asset) {
            $des = '';
            if (strpos($asset["path"], 'assets/') !== false) {
                $des = 'public/' . $asset["path"];
            } else {
                $des = $asset["path"];
            }
            // if updater need to replace files / folder (with/without content)
            if ($asset['action'] == 'replace') {
                if ($asset['type'] == 'file') {
                    copy(base_path('public/updater/' . $asset["path"]), base_path($des));
                }
                if ($asset['type'] == 'folder') {
                    $this->delete_directory(base_path($des));
                    $this->recurse_copy('public/updater/' . $asset["path"], $des);
                }
            }
            // if updater need to add files / folder (with/without content)
            elseif ($asset['action'] == 'add') {

                if ($asset['type'] == 'folder') {

                    $this->recurse_copy('public/updater/' . $asset["path"], $des);
                }
            }
        }

        $arr = ['WEBSITE_HOST' => $request->website_host];
        setEnvironmentValue($arr);
        Artisan::call('config:clear');
        // Artisan::call('migrate');


        $userDashboarnewdKeywords = [
            'Dashboard' => 'Dashboard',
            'Website_Information' => 'Website Information',
            'Dashboard_Language' => 'Dashboard Language',
            'Select a language' => 'Select a language',
            'Features_Section' => 'Features Section',
            'Offer_Banner_Section_(_Top_)' => 'Offer Banner Section ( Top )',
            'Offer_Banner_Section_(_Left_)' => 'Offer Banner Section ( Left )',
            'Offer_Banner_Section_(_Bottom_)' => 'Offer Banner Section ( Bottom )',
            'Featured Categories Section' => 'Featured Categories Section',
            'Footer Status Updated Successfully' => 'Footer Status Updated Successfully',
            'On_Sale_image_Subtitle' => 'On Sale Image Subtitle',
            'On_Sale_Image_Button_Name' => 'On Sale Image Button Name',
            'On_Sale_Image_Button_Link' => 'On Sale Image Button Link',
            'Enter_On_Sale_Image_Button_Link' => 'Enter On Sale Image Button Link',
            'Top_Rated_Item_Section_Image' => 'Top Rated Item Section Image',
            'Image_Title' => 'Image Title',
            'Button Link' => 'Button Link',
            'Popular Section' => 'Popular Section',
            'Popular Section Title' => 'Popular Section Title',
            'Enter Popular Section Title' => 'Enter Popular Section Title',
            'Gallery Section' => 'Gallery Section',
            'Gallery Section Title' => 'Gallery Section Title',
            'Enter Gallery Section Title' => 'Enter Gallery Section Title',
            'First delete all the items of those categories' => 'First delete all the items of those categories',
            'Gallery categories deleted successfully' => 'Gallery categories deleted successfully',
            'Gallery items deleted successfully' => 'Gallery items deleted successfully',
            'Gallery settings updated successfully' => 'Gallery settings updated successfully',
            'Gallery item updated successfully' => 'Gallery item updated successfully',
            'Gallery item unfeatured successfully' => 'Gallery item unfeatured successfully',
            'Gallery item featured successfully' => 'Gallery item featured successfully',
            'New gallery item added successfully' => 'New gallery item added successfully',
            'Slider' => 'Slider',
            'Post added for slider' => 'Post added for slider',
            'Post removed from slider' => 'Post removed from slider',
            'Post unfeatured successfully' => 'Post unfeatured successfully',
            'Post featured successfully' => 'Post featured successfully',
            'Theme_Thirteen' => 'Theme Thirteen',
            'Theme_Fourteen' => 'Theme Fourteen',
            'Featuded_Item_Section' => 'Featured Item Section',
            'Featured_Item_Section_Title' => 'Featured Item Section Title',
            'Enter_featured_item_title' => 'Enter featured item title',
            'Featured Category Section' => 'Featured Category Section',
            'Featured Category Items Section' => 'Featured Category Items Section',
            'Latest Section' => 'Latest Section',
            'On Sale Section' => 'On Sale Section',
            'Gallery_Items' => 'Gallery Items',
            'Video' => 'Video',
            'Toper_Subtitle' => 'Toper Subtitle',
            'Lower_Subtitle' => 'Lower Subtitle',
            'Second_Image' => 'Second Image',
            'Second_Subtitle' => 'Second Subtitle',
            'Third_Image' => 'Third Image',
            'Third_Title' => 'Third Title',
            'Third_Subtitle' => 'Third Subtitle',
            'Third_Button_Name' => 'Third Button Name',
            'Third_Button_URL' => 'Third Button URL',
            'The higher the serial number is, the later the category will be shown.' => 'The higher the serial number is, the later the category will be shown.',
            'Flash_Sale_Section' => 'Flash Sale Section',
            'Flash_Sale_Section_Title' => 'Flash Sale Section Title',
            'Enter_Featuded_Category_Item_Section_Title' => 'Enter featuded category item section title',
            'Featured_Category_Item_Section' => 'Featured Category Items Section',
            'Featured_Category_Item_Section_Title' => 'Featuded Category Item Section Title',
            'Latest_Item_Section' => 'Latest Item Section',
            'Latest_Item_Section_Title' => 'Latest Item Section Title',
            'Enter_Latest_Item_Section_Title' => 'Enter Latest Item Section Title',
            'On_Sale_Section' => 'On Sale Section',
            'On_Sale_Section_Title' => 'On Sale Section Title',
            'Enter_On_Sale_Section_Title' => 'Enter On Sale Section Title',
            'On_Sale_Section_Image' => 'On Sale Section Image',
            'Enter_On_Sale_Section_Section_Subtitle' => 'Enter On Sale Section Section Subtitle',
            'Enter_On_Sale_Section_Section_Button_Name' => 'Enter On Sale Section Section Button Name',
            'Gallery' => 'Gallery',
            'Specify whether the gallery category will be active or not.' => 'Specify whether the gallery category will be active or not.',
            'Gallery_Settings' => 'Gallery Settings',
            'Gallery_Management' => 'Gallery Management',
        ];
        $userFrontnewKeywords = [
            'wishlist' => 'wishlist',
            'No_Post_Found' => 'No Post Found',
            'Days' => 'Days',
            'Hours' => 'Hours',
            'Mins' => 'Mins',
            'Sec' => 'Sec',
            'Bookmark_List' => 'Bookmark List',
            'No_Bookmark_Found' => 'No Bookmark Found',
            'Views' => 'Views',
            'Date' => 'Date',
            'Title' => 'Title',
            'Action' => 'Action',
        ];

        $languages = Language::get();


        foreach ($languages as $language) {
            // get all the keywords of the selected language
            $jsonData = file_get_contents(resource_path('lang/') . 'user_' . $language->code . '.json');


            // convert json encoded string into a php associative array
            $keywords = json_decode($jsonData, true);
            $datas = array_merge($userDashboarnewdKeywords, $keywords);

            foreach ($keywords as $key => $keyword) {
                $datas[$key] = $keyword;
            }

            //put data
            $jsonData = json_encode($datas);

            $fileLocated = resource_path('lang/') . 'user_' . $language->code . '.json';

            // put all the keywords in the selected language file
            file_put_contents($fileLocated, $jsonData);
        }

        //for default json
        // get all the keywords of the selected language
        $jsonData = file_get_contents(resource_path('lang/') . 'user_default.json');

        // convert json encoded string into a php associative array
        $keywords = json_decode($jsonData, true);
        $datas = array_merge($userDashboarnewdKeywords, $keywords);

        foreach ($keywords as $key => $keyword) {
            $datas[$key] = $keyword;
        }
        //put data
        $jsonData = json_encode($datas);

        $fileLocated = resource_path('lang/') . 'user_default.json';

        // put all the keywords in the selected language file
        file_put_contents($fileLocated, $jsonData);



        foreach ($languages as $language) {

            $adlanguage = Language::where('id', $language->id)->first();
            // get all the keywords of the selected language
            $jsonData = $adlanguage->customer_keywords;


            // convert json encoded string into a php associative array
            $keywords = json_decode($jsonData, true);
            $datas = array_merge($userFrontnewKeywords, $keywords);

            foreach ($keywords as $key => $keyword) {
                $datas[$key] = $keyword;
            }

            //put data
            $jsonData = json_encode($datas);

            $adlanguage->customer_keywords = $jsonData;
            $adlanguage->save();
        }


        $userlanguages = UserLanguage::get();

        foreach ($userlanguages as $language) {

            $adlanguage = UserLanguage::where('id', $language->id)->first();
            // get all the keywords of the selected language
            $jsonData = $adlanguage->keywords;

            // convert json encoded string into a php associative array
            $keywords = json_decode($jsonData, true);
            $datas = array_merge($userFrontnewKeywords, $keywords);

            foreach ($keywords as $key => $keyword) {
                $datas[$key] = $keyword;
            }

            //put data
            $jsonData = json_encode($datas);

            $adlanguage->keywords = $jsonData;
            $adlanguage->save();
        }













        Session::flash('success', 'Updated successfully');
        return redirect('updater/success.php');
    }

    function delete_directory($dirname)
    {
        $dir_handle = null;
        if (is_dir($dirname))
            $dir_handle = opendir($dirname);
        if (!$dir_handle)
            return false;
        while ($file = readdir($dir_handle)) {
            if ($file != "." && $file != "..") {
                if (!is_dir($dirname . "/" . $file))
                    unlink($dirname . "/" . $file);
                else
                    $this->delete_directory($dirname . '/' . $file);
            }
        }
        closedir($dir_handle);
        rmdir($dirname);
        return true;
    }

    public function redirectToWebsite(Request $request)
    {
        $arr = ['WEBSITE_HOST' => $request->website_host];
        setEnvironmentValue($arr);
        Artisan::call('config:clear');

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