<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Helper\Helper;

class InstallController extends Controller
{
    public function installation(Request $request)
    { 
        if ($request->isMethod('post')) {

            $data = [
              'is_install' => true,
              'license_key' => $request->license_key,
              'server_ip' => $_SERVER['SERVER_ADDR'],
              'domain' =>  $request->app_url,
              'email' => $request->email
            ];

            $result = json_decode(Helper::verifyLicense($data), true);

            $js_challange_enabled = false;
            if(!empty($result['verify']) && $result['verify']) {
              $verfied = true;
            } else {
              try {
                if($result['verify'] == false) {
                  // Relayzo's Unverefied 
                  $verfied = false;
                } else {
                  // JS challange Enabled
                  $verfied = true;
                }
              } catch (\Exception $e) {
                // JS challange Enabled
                $verfied = true;
              }
            }
            
            if($verfied) {
              $create_db = $this->_createDB($request->db_host, $request->db_username, $request->db_password, $request->db_name);
              if(!empty($request->db_name) && $create_db == 'success') {
                  $evn_file_settings = $this->_envFile($request->db_host, $request->db_username, $request->db_password, $request->db_name, $request->tables_prefix);

                  if($evn_file_settings == 'success' && $create_db == 'success') {

                    // DB Migration and Seeding
                    $message = $this->_migrate();

                    // Update superadmin
                    $user_settings = $this->_updateUserSettings($request->all());
                    if($user_settings == 'success') {

                      $data = [
                        'is_install_complete' => true,
                        'license_key' => $request->license_key,
                        'server_ip' => $_SERVER['SERVER_ADDR'],
                        'domain' =>  $request->app_url,
                        'email' => $request->email
                      ];
                      Helper::verifyLicense($data);

                      $fp = fopen(storage_path('app/installed'), 'w');
                      fclose($fp);

                      $message = Helper::getCronCommand();
                      return response()->json(['success' => true, 'msg' => $message]);
                    } else {
                      return response()->json(['success' => false, 'msg' => "<strong class='text-danger'>ERROR:</strong> $user_settings"]);
                    }
                  } else {
                    return response()->json(['success' => false, 'msg' => "<strong class='text-danger'>ERROR:</strong> $evn_file_settings"]);
                  }
              } else {
                   return response()->json(['success' => false, 'msg' => "<strong class='text-danger'>ERROR:</strong> $create_db"]);
              }
          } else {
            return response()->json(['success' => false, 'msg' => "<strong class='text-danger'>ERROR:</strong> ". print_r($result['message'], true)]);
          }
        }
    }

    private function _envFile($host, $username, $password, $db_name, $tables_prefix)
    {
        $env_settings = 'DB_CONNECTION=mysql
DB_HOST=' . $host . '
DB_DATABASE=' . $db_name . '
DB_USERNAME=' . $username . '
DB_PASSWORD=' . $password . '
TBL_PREFIX=' . $tables_prefix;

          try {
            file_put_contents(base_path('.env'), $env_settings);
            \Artisan::call('config:cache');
            return 'success';
          } catch (\Exception $e) {
            //return 'Please check .env file permissions. It should be 0777';
            return $e->getMessage();
          }
      }

      private function _createDB($host, $username, $password, $db_name)
      { 
        try {
          $dbh = new \PDO('mysql:host=' . $host, $username, $password);
          $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
          // First check if database exists
          $dbh->query('CREATE DATABASE IF NOT EXISTS `'.$db_name.'` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;');

          try {
            $con = mysqli_connect($host, $username, $password, trim($db_name));
            if($con) {
              return 'success';
            } else {
              return mysqli_connect_error();
            }
          } catch (\Exception $e) {
            return $e->getMessage();
          }  
        } catch (\Exception $e) {
          return $e->getMessage();
        }

      }

      private function _migrate()
      {
        try {
          \Artisan::call('migrate', ["--force" => true]);
        } catch (\Exception $e) {
          return $e->getMessage();
        }
        // DB Seeding
        $this->_seed();
      }

      private function _seed()
      {
        try {
          \Artisan::call('db:seed', ["--force" => true]);
        } catch (\Exception $e) {
          return $e->getMessage();
        }
      }

      private function _updateUserSettings($request) {
        try {
          // Get superadmin detail as come with application
          $user = \App\Models\User::findOrFail(config('custom.superadmin'));
          $request['password'] = bcrypt($request['password']);
          $request['name'] = $request['app_name'];
          $user->fill($request)->save();
        } catch (\Exception $e) {
          return $e->getMessage();
        }

        // Update Settings
        try {
          $app_url = str_replace('www.', '', $request['app_url']);
          \DB::table('settings')->whereId(config('custom.app_id'))->update([
            'app_name' => $request['app_name'],
            'app_url' => $app_url,
            'license_key' => $request['license_key'],
            'server_ip' => $_SERVER['SERVER_ADDR'],
            'current_version' => substr(Helper::getUrl(config('custom.version_live_url')), 0, 10),
            'created_at' => \Carbon\Carbon::now(),
            'updated_at'=> \Carbon\Carbon::now(),
          ]);
        } catch (\Exception $e) {
          return $e->getMessage();
        }
        return 'success';
      }
}
