<?php

namespace Webuccino\Install\Core\Middleware;

use Webuccino\Install\Core\App;
use Webuccino\Install\Core\Database;

class NonInstalled
{
    public function handle()
    {

        if (check_installed()) {
            $this->resetDB();
            if (urlIs('/importDatabase')) {
                $prefix = config_native("srm_config.installer.table_prefix");

                echo json_encode([
                    "msg" => "The installation has already been completed in this database, so you can go to the login page and begin using it. If you'd like to reinstall, please delete all tables in the database that start with \"$prefix\". Otherwise, you will be redirected to the login page to start using Smart Report Maker."
                ]);
                exit;
            }

            return redirect_native(route_native('/finishInstallation'));
            exit;
        }

    }


    private function resetDB(){

        $status = config_native('srm_install_config.status');
        
        $config = config_native('srm_db_config');
        
        if ($config) {
            
            $db = App::resolve(Database::class);
            $db->initiateConnection(
                $config["driver"],
                $config["host"],
                $config["database"],
                $config["username"],
                $config["password"],
                $config["port"]
            );
            
            $mail = $db->first('mail',['is_default' => 1]);
            
            if($mail){
                try {
                    decrypt_native($mail->Password);
                } catch (\Exception $e) {

                    $db->truncate('mail');
                }
            }
        }
    }

}