<?php
namespace App\Services;

use App\Services\Util;
use App\Models\Setting;
use App\Mail\MailCredit;
use App\Models\UserCredit;
use Illuminate\Support\Facades\Mail;

class Credit
{

    public static function getCreditNumber(){
        return (int) Setting::getContentBySlug('credit-number');
    }


    public static function makeNextCreditNumber(){
        $credit_number = self::getCreditNumber();
        $credit_number = $credit_number+1;
        Setting::setContentBySlug('credit-number', $credit_number, 'int');
        return $credit_number;
    }

    public static function createCreditNumber($credit_number, $credit_date){
        $prefix = "GS".\Carbon::parse($credit_date)->format('Ym');
        return $prefix.$credit_number;
    }

    public static function getCreditStorageDir($credit_date){
        return "/credit/".\Carbon::parse($credit_date)->format('Y/m/');
    }

    public static function makeCreditFilename($credit_number){
        return "Gutschrift-".$credit_number.".pdf";
    }

    public static function isCredit(UserCredit $user_credit){
        return isset($user_credit->credit['filename']) ? true : false;
    }

    public static function getFilename(UserCredit $user_credit){
        return isset($user_credit->credit['filename']) ? $user_credit->credit['filename'] : false;
    }

  
    public static function getDir(UserCredit $user_credit){
        return isset($user_credit->credit['dir']) ? $user_credit->credit['dir'] : false;
    }

    public static function getDownloadURL(UserCredit $user_credit, $do = false){
        return route('storage_file', [$user_credit->id, 'cms_download_file', $do]);
    }
   
    public static function getDownloadPath(UserCredit $user_credit, $full = false){
        $dir = self::getDir($user_credit);
        $filename = self::getFilename($user_credit);
        if(!$full){
            return $dir.$filename;
        }
        return \Storage::disk('public')->path($dir.$filename);
    }

    public static function sendCreditMail(UserCredit $user_credit){
        $bcc = [];
        $email = $user_credit->user->email;
        if(!$email){
            if($user_credit->user->mode === 'test'){
            }else{
                $email = config('app.checkout_mail');
            }
        }
        if($user_credit->user->mode === 'test'){
            $bcc[] = config('app.checkout_test_mail');
        }else{
            $bcc[] = config('app.checkout_mail');
        }
        Mail::to($email)->bcc($bcc)->send(new MailCredit($user_credit));
    }
}
