<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coin_Package;
use App\Models\Coin_Package_Transaction;
use App\Models\Comment;
use App\Models\Common;
use App\Models\Creator_Package;
use App\Models\Creator_Package_Transaction;
use App\Models\Creator_Request;
use App\Models\Gift;
use App\Models\Hashtag;
use App\Models\Like;
use App\Models\Live_History;
use App\Models\Live_User;
use App\Models\Notification;
use App\Models\OnboardingScreen;
use App\Models\Page;
use App\Models\Post;
use App\Models\Post_Content;
use App\Models\Read_Notification;
use App\Models\Report;
use App\Models\Report_Reason;
use App\Models\Social_Link;
use App\Models\Story;
use App\Models\Story_View;
use App\Models\User;
use App\Models\User_Block;
use App\Models\View;
use App\Models\Withdrawal_Request;
use Illuminate\Support\Facades\DB;
use Exception;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class SystemSettingController extends Controller
{
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index()
    {
        try {

            $params['data'] = [];
            return view('admin.system_setting.index', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function ClearData()
    {
        try {

            // Folder Name
            $app = 'public/app';
            $coin_package = 'public/coin_package';
            $creator_package = 'public/creator_package';
            $gift = 'public/gift';
            $hashtag = 'public/hashtag';
            $notification = 'public/notification';
            $post = 'public/post';
            $story = 'public/story';
            $user = 'public/user';

            // Name Array
            $app_name = [];
            $coin_package_name = [];
            $creator_package_name = [];
            $gift_name = [];
            $hashtag_name = [];
            $notification_name = [];
            $post_name = [];
            $story_name = [];
            $user_name = [];

            // Get Files
            $app_file = Storage::allFiles($app);
            $coin_package_file = Storage::allFiles($coin_package);
            $creator_package_file = Storage::allFiles($creator_package);
            $gift_file = Storage::allFiles($gift);
            $hashtag_file = Storage::allFiles($hashtag);
            $notification_file = Storage::allFiles($notification);
            $post_file = Storage::allFiles($post);
            $story_file = Storage::allFiles($story);
            $user_file = Storage::allFiles($user);

            // Add Name In Array
            foreach ($app_file as $app_file) {
                array_push($app_name, pathinfo($app_file)['basename']);
            }
            foreach ($coin_package_file as $coin_package_file) {
                array_push($coin_package_name, pathinfo($coin_package_file)['basename']);
            }
            foreach ($creator_package_file as $creator_package_file) {
                array_push($creator_package_name, pathinfo($creator_package_file)['basename']);
            }
            foreach ($gift_file as $gift_file) {
                array_push($gift_name, pathinfo($gift_file)['basename']);
            }
            foreach ($hashtag_file as $hashtag_file) {
                array_push($hashtag_name, pathinfo($hashtag_file)['basename']);
            }
            foreach ($notification_file as $notification_file) {
                array_push($notification_name, pathinfo($notification_file)['basename']);
            }
            foreach ($post_file as $post_file) {
                array_push($post_name, pathinfo($post_file)['basename']);
            }
            foreach ($story_file as $story_file) {
                array_push($story_name, pathinfo($story_file)['basename']);
            }
            foreach ($user_file as $user_file) {
                array_push($user_name, pathinfo($user_file)['basename']);
            }
            
            // Delete File In Folder
            foreach ($app_name as $key => $value) {

                $app_file_check = Page::select('id')->where('icon', $value)->first();
                $app_file_check_1 = Social_Link::select('id')->where('image', $value)->first();
                $app_file_check_2 = OnboardingScreen::select('id')->where('image', $value)->first();

                $settingData = Setting_Data();
                $app_file_check_3 = 'yes';
                if ($settingData['app_logo'] != $value) {
                    $app_file_check_3 = 'no';
                }

                if ($app_file_check == null && $app_file_check_1 == null && $app_file_check_2 == null && $app_file_check_3 == 'no') {
                    $this->common->deleteImageToFolder('app', $value);
                }
            }
            foreach ($coin_package_name as $key => $value) {

                $coin_package_file_check = Coin_Package::select('id')->where('image', $value)->first();
                if ($coin_package_file_check == null) {
                    $this->common->deleteImageToFolder('coin_package', $value);
                }
            }
            foreach ($creator_package_name as $key => $value) {

                $creator_package_file_check = Creator_Package::select('id')->where('image', $value)->first();
                if ($creator_package_file_check == null) {
                    $this->common->deleteImageToFolder('creator_package', $value);
                }
            }
            foreach ($gift_name as $key => $value) {

                $gift_file_check = Gift::select('id')->where('image', $value)->first();
                if ($gift_file_check == null) {
                    $this->common->deleteImageToFolder('gift', $value);
                }
            }
            foreach ($hashtag_name as $key => $value) {

                $hash_file_check = Hashtag::select('id')->where('image', $value)->first();
                if ($hash_file_check == null) {
                    $this->common->deleteImageToFolder('hashtag', $value);
                }
            }
            foreach ($notification_name as $key => $value) {

                $notification_file_check = Notification::select('id')->where('image', $value)->first();
                if ($notification_file_check == null) {
                    $this->common->deleteImageToFolder('notification', $value);
                }
            }
            foreach ($post_name as $value) {
                $post_file_check = Post_Content::select('id')->where('content_url', $value)->orwhere('content_image', $value)->first();
                if ($post_file_check === null) {
                    $this->common->deleteImageToFolder('post', $value);
                }
            }            
            foreach ($story_name as $key => $value) {

                $story_file_check = Story::select('id')->where('url', $value)->first();
                if ($story_file_check == null) {
                    $this->common->deleteImageToFolder('story', $value);
                }
            }
            foreach ($user_name as $key => $value) {

                $user_file_check = User::select('id')->where('image', $value)->orwhere('cover_img', $value)->orwhere('front_id_proof_img', $value)->orwhere('back_id_proof_img', $value)->first();
                $creator_request_file_check = Creator_Request::select('id')->where('front_id_proof_img', $value)->orwhere('back_id_proof_img', $value)->first();
                if ($user_file_check == null && $creator_request_file_check == null) {
                    $this->common->deleteImageToFolder('user', $value);
                }
            }
           
            return response()->json(array('status' => 200, 'success' => __('Label.data_clear_successfully')));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function DownloadSqlFile()
    {
        try {

            Artisan::call('config:clear');

            $storageAt = storage_path() . "/app/public/database";
            if (!file_exists($storageAt)) {
                File::makeDirectory($storageAt, 0755, true, true);
            }

            $mysqlHostName = env('DB_HOST');
            $mysqlUserName = env('DB_USERNAME');
            $mysqlPassword = env('DB_PASSWORD');
            $DbName = env('DB_DATABASE');

            // get all table name
            $result = DB::select("SHOW TABLES");
            $prep = "Tables_in_$DbName";

            foreach ($result as $res) {
                $tables[] =  $res->$prep;
            }

            $connect = new \PDO("mysql:host=$mysqlHostName;dbname=$DbName;charset=utf8", "$mysqlUserName", "$mysqlPassword", array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
            $statement = $connect->prepare("SHOW TABLES");
            $statement->execute();
            $result = $statement->fetchAll();

            $output = '';
            foreach ($tables as $table) {

                $show_table_query = "SHOW CREATE TABLE " . $table . "";
                $statement = $connect->prepare($show_table_query);
                $statement->execute();
                $show_table_result = $statement->fetchAll();

                foreach ($show_table_result as $show_table_row) {
                    $output .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
                }
                $select_query = "SELECT * FROM " . $table . "";
                $statement = $connect->prepare($select_query);
                $statement->execute();
                $total_row = $statement->rowCount();

                for ($count = 0; $count < $total_row; $count++) {
                    $single_result = $statement->fetch(\PDO::FETCH_ASSOC);
                    $table_column_array = array_keys($single_result);
                    $table_value_array = array_values($single_result);
                    $output .= "\nINSERT INTO $table (";
                    $output .= "`" . implode("`, `", $table_column_array) . "`) VALUES (";
                    $output .= "'" . implode("', '", $table_value_array) . "');\n";
                }
            }

            $file_name = App_Name() . '_db_' . date('d_m_Y') . '.sql';
            $file_handle = fopen(storage_path() . '/app/public/database/' . $file_name, 'w+');
            fwrite($file_handle, $output);
            fclose($file_handle);
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($file_name));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize(storage_path() . '/app/public/database/' . $file_name));
            ob_clean();
            flush();
            readfile(storage_path() . '/app/public/database/' . $file_name);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function CleanDatabase()
    {
        try {

            Coin_Package::query()->truncate();
            Coin_Package_Transaction::query()->truncate();
            Comment::query()->truncate();
            Creator_Package::query()->truncate();
            Creator_Package_Transaction::query()->truncate();
            Creator_Request::query()->truncate();
            Gift::query()->truncate();
            Hashtag::query()->truncate();
            Like::query()->truncate();
            Live_History::query()->truncate();
            Live_User::query()->truncate();
            Notification::query()->truncate();
            OnboardingScreen::query()->truncate();
            Post::query()->truncate();
            Post_Content::query()->truncate();
            Read_Notification::query()->truncate();
            Report::query()->truncate();
            Report_Reason::query()->truncate();
            Social_Link::query()->truncate();
            Story::query()->truncate();
            Story_View::query()->truncate();
            User::query()->truncate();
            User_Block::query()->truncate();
            View::query()->truncate();
            Withdrawal_Request::query()->truncate();

            return response()->json(array('status' => 200, 'success' =>  __('Label.data_clean_successfully')));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
