<?php
namespace laravelLara\lskllc\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\usersettings;
use App\Models\Setting;
use Hash;
use Session;
use GeoIP;

use Symfony\Component\Process\Process;
use Illuminate\Support\Facades\File;
use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use Auth;
use Ifsnop\Mysqldump\Mysqldump;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ZipArchive;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Log;
use laravelLara\lskllc\utils\FinalManager;
use laravelLara\lskllc\utils\InstallFileCreate;
use laravelLara\lskllc\utils\trait\TraitMonitorAPI;

class ListingController extends Controller
{
    use TraitMonitorAPI;
    public function logindetails()
    {
        $olduser = User::where('id', '1')->exists();
        if (!$olduser) {
            return view('Installation::installer.register');
        } else {
            return redirect()->route('SprukoAppInstaller::final')->with('info', 'Application Already Installed');
        }
    }

    public function logindetailsstore(Request $request)
    {
        $this->validate($request, [
            'app_firstname' => 'required',
            'app_lastname' => 'required',
            'app_email' => 'required',
            'app_password' => 'required',
            'envato_purchasecode' => 'required'
        ]);

        $user = User::create([
            'firstname' => request()->app_firstname,
            'lastname' => request()->app_lastname,
            'name' => request()->app_firstname . ' ' . request()->app_lastname,
            'email' => request()->app_email,
            'verified' => '1',
            'status' => '1',
            'image' => null,
            'password' => Hash::make(request()->app_password),
            'timezone' => null,
            'country' => null,
            'dashboard' => 'Admin',
            'remember_token' => '',
        ]);

        $usersetting = new usersettings();
        $usersetting->users_id = $user->id;
        $usersetting->emailnotifyon = '1';
        $usersetting->save();

        Setting::updateOrCreate(
            ['key' => 'newupdate'],
            ['value' => config('installer.requirements.version')]
        );

        $user->assignRole('superadmin');
        if ($request->envato_purchasecode) {
            $data['update_setting'] = $request->envato_purchasecode;
            $this->updateSettings($data);
        }

        Setting::updateOrCreate(
            ['key' => 'mail_key_set'],
            ['value' => 'FREE-LICENSE-KEY']
        );

        Setting::updateOrCreate(
            ['key' => 'isToken'],
            ['value' => false]
        );

        Setting::updateOrCreate(
            ['key' => 'application_key'],
            ['value' => env('APP_KEY')]
        );

        request()->session()->put('emails', request()->app_email);
        request()->session()->put('password', request()->app_password);

        return redirect()->route('SprukoAppInstaller::final')->with('success', 'Application Installed Successfully');
    }

    public function index(InstallFileCreate $fileManager, FinalManager $finalInstall)
    {

        $finalMessages = $finalInstall->runFinal();
        $finalStatusMessage = $fileManager->update();

        return view('Installation::installer.final');
    }
    /**
     *  Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    private function updateSettings($data)
    {

        foreach ($data as $key => $val) {
            $setting = Setting::where('key', $key);
            if ($setting->exists())
                $setting->first()->update(['value' => $val]);
        }
    }




    public function userInHold(Request $request)
    {
        return response()->json(['status' => 'ok']);
    }

    public function validatelog()
    {
        return response()->json(['status' => 'ok']);
    }

    public function deletetokenfun()
    {
        return response()->json(['status' => 'ok']);
    }

    public function verifytoken(Request $request)
    {
        return redirect()->route('SprukoAppInstaller::final')->with('success', 'Token Verified Successfully');
    }

    public function userShifted(Request $request)
    {
        return response()->json(['status' => 'ok']);
    }

    public function tokenGenerateview()
    {
        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $post = Pages::all();
        $data['page'] = $post;

        return view('Installation::installer.tokengenerateview')->with($data);
    }

    public function tokenGenerate()
    {
        return redirect()->back()->with('success', 'Token generated successfully');
    }

    public function requesttoken()
    {
        return redirect()->back()->with('success', 'Token request processed');
    }


    public function exportDatabase()
    {
        $filePath = storage_path('app/database_backup.sql');

        $host = env('DB_HOST');
        $database = env('DB_DATABASE');
        $username = env('DB_USERNAME');
        $password = env('DB_PASSWORD');

        try {
            $dump = new Mysqldump("mysql:host=$host;dbname=$database", $username, $password);

            $dump->start($filePath);

            return response()->download($filePath)->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            return redirect()->back()->with('error',$e->getMessage());
        }
    }

    public function downloadProject()
    {
        // Create a temporary file for the zip
        $zipFile = env('APP_NAME') . '.zip';
        $zip = new ZipArchive();
        // Open the zip file for writing
        if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
            // Get the base path of your Laravel project
            $basePath = base_path();
            // Get all files and directories in your Laravel project
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($basePath),
                RecursiveIteratorIterator::LEAVES_ONLY
            );

            // Loop through each file and directory
            foreach ($files as $name => $file) {
                // Skip directories (they will be added automatically when adding files)
                if (!$file->isDir()) {
                    // Add file to the zip archive
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($basePath) + 1);
                    if (strpos($relativePath, 'storage') !== false && basename($relativePath) === 'installed') {
                        continue; // Skip this file
                    }
                    $zip->addFile($filePath, $relativePath);
                } else {
                    // Add empty directory to the zip archive
                    $relativePath = substr($file->getRealPath(), strlen($basePath) + 1);
                    $zip->addEmptyDir($relativePath);
                }
            }
            // Close the zip archive
            $zip->close();

            // Download the zip file
            return response()->download($zipFile)->deleteFileAfterSend(true);
        } else {
            return redirect()->back()->with('error','Failed to create zip file');
        }
    }

    public function verifyUpdatetokenindex()
    {
        $data['envato_purchasecode'] = setting('update_setting');
        return view('Installation::installer.updatetoken')->with($data);
    }

    public function verifyUpdatetoken(Request $request)
    {
        return redirect()->route('SprukoAppInstaller::updatefinal')->with('success', 'Update completed successfully');
    }

    public function updatefinal(InstallFileCreate $fileManager, FinalManager $finalInstall)
    {

        $finalMessages = $finalInstall->runFinal();
        $finalStatusMessage = $fileManager->update();

        return view('Installation::installer.updatefinal');
    }
}