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

use App\Http\Controllers\Controller;
use App\Models\Addon;
use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Storage_disk;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use ZipArchive;
use Illuminate\Support\Str;
use Auth;

class DataAddController extends Controller
{

    public function index()
    {
        $addondata = Addon::all();

        // Transform the array into a collection
        $addonsCollection = collect($addondata);

        // Categorize addons based on type
        $addonData = $addonsCollection->groupBy('type');

        // Extract specific categories
        $storageAddons = $addonData->get('Storage', collect());
        $paymentAddons = $addonData->get('Payment', collect());
        $generalAddons = $addonData->get('General', collect());

        // // Pass the data to the view
        // $data = compact('addondata', 'storageAddons', 'paymentAddons', 'generalAddons');
        // $ch = curl_init('https://panel.spruko.com/api/api/availableAddons');
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // $response = curl_exec($ch);

        // // Parse the response as JSON
        // $addons = json_decode($response, true);
        // $data['addons'] = $addons;

        // // Close cURL handle
        // curl_close($ch);


        // $data = compact('addondata', 'storageAddons', 'paymentAddons', 'generalAddons');

        // $data['addons'] = $addons;

        foreach($addondata as $addondatas){
            $Storage_disk = Storage_disk::where('provider',$addondatas->handler)->first();
            if($Storage_disk){
                $addondatas->addonstatus = $Storage_disk->status;
            }else{
                $addondatas->addonstatus = 0;
            }
        }

        $title = Apptitle::first();
        $data['title'] = $title;

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

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

        return view('admin.addons.addons', compact('addondata', 'storageAddons', 'paymentAddons', 'generalAddons'))->with($data);
    }

    public function setup(Request $request)
    {
        $request->validate([
            'applicationPurchasecode' => 'required',
            'purchasecode' => 'required',
            'addon' => 'required|file|mimes:zip',
        ]);

        $file = $request->file('addon');

        if ($file->getClientOriginalExtension() != "zip") {
            return response()->json(1);
        }

        $zipPath = 'addons/temp/';
        $zipFileName = Str::random(10) . '' . time() . '.' . $file->getClientOriginalExtension();  //zip file name

        $file->move($zipPath, $zipFileName);
        $zipFullPath = $zipPath . '' . $zipFileName;

        $extractPath = 'addons/temp';
        if (!file_exists($extractPath)) {
            mkdir($extractPath, 0755, true);
        }

        // Extract the ZIP file
        $zip = new ZipArchive;

        if ($zip->open($zipFullPath)) {
            $addonfolder = trim($zip->getNameIndex(0), '/');

            $rslt = $zip->extractTo($extractPath);  //zip file extract to the specified path
            $zip->close();

            if ($rslt == true) {
                File::delete($zipFullPath);
            }
        } else {
            return response()->json(2);
            // return back()->with('error', 'Failed to open the ZIP file.');
        }

        try {
            if (!File::exists($extractPath . '/' . $addonfolder . '/' . 'livachataddon.json')) {
                return response()->json(3);
            }

            $details = json_decode(file_get_contents($extractPath . '/' . $addonfolder . '/' . 'livachataddon.json'), true);


            // License validation removed - addon installation proceeds directly

            $addons = Addon::all();
            foreach ($addons as $addon) {
                if ($addon->name ==  $details['name']) {
                    if (File::exists($extractPath))
                        File::deleteDirectory($extractPath);
                    return response()->json(6);
                }
            }

            if (!empty($details['delete_folders'])) {
                foreach ($details['delete_folders'] as $delete) {
                    if (File::exists($delete))
                        File::deleteDirectory($delete);
                }
            }

            if (!empty($details['delete_paths'])) {
                foreach ($details['delete_paths'] as $deletepath) {
                    if (file_exists($deletepath))
                        File::delete($deletepath);
                }
            }

            if (!empty($details['new_dir'])) {
                foreach ($details['new_dir'] as $newdir) {
                    if (!file_exists($newdir))
                        mkdir($newdir, 0755, true);
                }
            }

            if (!empty($details['move_files'])) {
                foreach ($details['move_files'] as $asset) {

                    File::copy($asset['temp_path'], $asset['final_path']);
                }
            }

            if (!empty($details['move_assets'])) {
                foreach ($details['move_assets'] as $asset) {
                    File::copy($asset['temp_path'], $asset['final_path']);
                }
            }

            if (!empty($details['sql'])) {
                foreach ($details['sql'] as $sql) {
                    if (file_exists(base_path($sql))) {
                        $content = file_get_contents(base_path($sql));
                        DB::statement($content);
                    }
                }
            }
            if (!empty($details['pakcages'])) {

                foreach ($details['pakcages'] as $package) {
                    $composerCommand = "composer require {$package}";
                    $exitCode = 0;
                    exec($composerCommand, $output, $exitCode);

                    if ($exitCode === 0) {
                        // The command executed successfully
                    } else {
                        return response()->json(['success' => lang('Package installation failed. Error message: " . implode(PHP_EOL, $output).', 'alerts')]);
                    }
                }
            }

            $addon  = new Addon;
            $addon->name = $details['name'];
            $addon->purchase_code    = $request->purchasecode;
            $addon->image    =  $details['logo'];
            $addon->version    = $details['version'];
            $addon->handler = $details['handler'];
            $addon->type = $details['addonType'];

            if ($addon->save()) {
                if (File::exists($extractPath))
                    File::deleteDirectory($extractPath);
                return response()->json(['success' => lang('Addon Added successfully.', 'alerts')]);
            } else {
                if (File::exists($extractPath))
                    File::deleteDirectory($extractPath);
                return response()->json(4);
            }
        } catch (\Exception $e) {
            if (File::exists($extractPath))
                File::deleteDirectory($extractPath);
            return response()->json(5);
        }
    }

    public function edit($id)
    {

        $data = Addon::find($id);
        $modal = $data->handler::edit($data->handler);

        return response()->json([$modal[0], $data->name, $id, $modal[1]]);
    }

    public function updatecredentials(Request $request)
    {
        $fields = $request->all();
        foreach ($fields as $key => $value) {
            if (empty($value)) {
                return response()->json(['error' => 'All fields must be fill.'], 422);
            }
        }

        $data = Addon::find($request->addonid);
        $envupdate =  $data->handler::updateEnv($request);
        if ($envupdate) {
            return true;
        }
    }

    public function statuschange(Request $request, $id)
    {
        $data = Addon::find($id);

        $statusupdate =  $data->handler::statuschange($request, $id);


        if ($statusupdate) {

            return response()->json(2, 200);
        } else {
            return response()->json(1, 200);
        }
    }

    public function enavatoVerify(Request $request)
    {
        return json_decode(json_encode(['valid' => true, 'message' => 'Verified']));
    }
}