<?php

namespace App\Http\Controllers;
use App\Http\Helper\Helper;
use Auth;

use Illuminate\Http\Request;

class ToolController extends Controller
{
    public function update()
    {
        Helper::checkPermissions('update');
        $settings = \App\Models\Setting::find(config('custom.app_id'));
        $settings->available_version = Helper::getUrl(config('custom.version_live_url'));
        return view('tools.update', compact('settings'));
    }

    public function updateApp(Request $request)
    {
        $settings = \App\Models\Setting::find(config('custom.app_id'));
        $data = [
          'is_update' => true,
          'license_key' => $settings->license_key,
          'server_ip' => $_SERVER['SERVER_ADDR']
        ];
        $result = json_decode(Helper::verifyLicense($data), true);

        if($result['verify']) {
          // Copy updated files
          try {
            $file = config('custom.update_download_url').$settings->license_key.'.zip';
            $dest_file = storage_path().DIRECTORY_SEPARATOR.'update.zip';
            copy($file, $dest_file);
            try {
              //chmod($dest_file, 0777);
            } catch (\Exception $e) {
              return $result['message'] = $e->getMessage();
            }
            
          } catch (\Exception $e) {
            return $result['message'] = $e->getMessage();
          }

          // Extract files
          try {
            $zip = new \ZipArchive;
            if ($zip->open($dest_file) === true) {
                // Extract to the desired path
                $zip->extractTo(base_path());
                $zip->close();
            } else {
                return $result['message'] = 'File did not extract';
            }
          } catch (\Exception $e) {
            return $result['message'] = $e->getMessage();
          }

          // Config, Cache, and View Clear
          \Artisan::call('config:cache');
          \Artisan::call('cache:clear');
          \Artisan::call('view:clear');

          // Migration
          try {
            \Artisan::call('migrate', ["--force" => true]);
          } catch (\Exception $e) {
            return $result['message'] = $e->getMessage();
          }

          // Update version file
          try {
            // Save version into db
            \DB::table('settings')->whereId(config('custom.app_id'))->update([
              'current_version' => Helper::getUrl(config('custom.version_live_url'))
            ]);
          } catch (\Exception $e) {
            return $result['message'] = $e->getMessage();
          }

          // Delete donwloaded file after successful update
          try {
            unlink($dest_file);
          } catch (\Exception $e) {
            return $result['message'] = $e->getMessage();
          }

          // Check app updated completely
          $data = [
            'is_complete' => true,
            'license_key' => $settings->license_key,
          ];

          return json_decode(Helper::verifyLicense($data), true);
        } else {
          $data = [
            'verify' => false,
            'message' => 'Invalid license key',
          ];
          return json_encode($data);
        }
    }

    public function helpSend(Request $request) 
    {
      $request->validate([
        'subject' => 'required',
        'detail' => 'required'
      ]);

      $settings = \App\Models\Setting::find(config('custom.app_id'));

      if(empty($settings->from_email)) {
        echo '<span class="text-danger">'.__('app.help_no_from_name').'</span>';
      }

      $from_email = $settings->from_email;
      $from_name = $settings->from_name;
      // get sending domain from email
      $sending_domain = Helper::getSendingDomainFromEmail($from_email);
      $tracking_domain = $sending_domain->protocol.$sending_domain->domain;
      $message_id = Helper::getCustomMessageID($tracking_domain);

      $message = new \Symfony\Component\Mime\Email();
      $message->from(new \Symfony\Component\Mime\Address($from_email, $from_name));

      $connection = Helper::configureSendingNode($settings->sending_type, $settings->sending_attributes);
      if(in_array($settings->sending_type, Helper::sendingServersFramworkSuported())) {
        $headers= $message->getHeaders();
        $headers->addIdHeader('Message-ID', $message_id);
        $headers->addTextHeader('List-Unsubscribe', sprintf('<mailto:%s?subject=unsubscribe>', urlencode($from_email)));
        $headers->addTextHeader('List-Unsubscribe-Post', 'List-Unsubscribe=One-Click');

        $message->to(config('custom.help_email'));
        $message->subject($request->subject);
        $message->html($request->detail);
        $message->text($request->detail);
        try {
            $connection['transport']->send($message);
            echo '<span class="text-success">'.__('app.help_successfully_sent').'</span>';
        } catch(\Exception $e) {
            echo $e->getMessage();
            echo '<span class="text-danger">'.__('app.help_failed_sent').'</span>';
        }
      } elseif($settings->sending_type == 'sendgrid_api') {
        $message->addTo(config('custom.help_email'));
        $message->setSubject($request->subject);
        $message->addContent("text/html", $request->detail);
        $sendgrid = new \SendGrid(json_decode($settings->sending_attributes)->api_key);
        try {
          $response = $sendgrid->send($message);
          echo '<span class="text-success">'.__('app.help_successfully_sent').'</span>';
        } catch(\Exception $e) {
          //echo $e->getMessage();
          echo '<span class="text-danger">'.__('app.help_failed_sent').'</span>';
        }
      }

    }
}
