<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

use App\Http\Services\EmailService;
use App\Models\PromoCode;
use App\Models\StoreOrder;
use App\Models\User;

class EmailTestController extends Controller
{
    public $appUrl;
    protected $emailService;
    public $appInternalName;
    public $stringMappingConfig;

    public function __construct(EmailService $emailService)
    {
        parent::__construct();
        $this->appUrl = config('app.url');
        $this->emailService = $emailService;
        $this->appInternalName = config('app.internalName');
        $this->stringMappingConfig = config('constants.' . $this->appInternalName );
    }

    public function previewEmail($email = null)
    {
        $appInternalName = $this->appInternalName;
        $stringMappingConfig = $this->stringMappingConfig;
        if($email){
            $destinationPath = resource_path('views/emails/templates/' . $email . '.blade.php');
            if(File::exists($destinationPath)){
                $content = File::get($destinationPath);
                $user = $this->user;
                $appUrl = $this->appUrl;
                $emailFromName = '[EMAIL_FROM_NAME]';
                $storeOrder = StoreOrder::first();
                return view('emails/templates/' . $email, compact('user', 'appUrl', 'stringMappingConfig', 'appInternalName', 'emailFromName', 'storeOrder',));
            } 
            else {
                abort(404);
            }
        }
        $files = File::allFiles(resource_path('views/emails/templates/'));

        $fileNames = [];
        foreach ($files as $file) {
            $fileName = $file->getFilename();
            $fileNameParts = explode('.', $fileName);
            $fileRef = @$fileNameParts[0];
            if($fileRef) array_push($fileNames, $fileRef);
        }

        return view('app.preview-email', compact('fileNames'));
    }
}
