<?php

namespace App\Helpers;

use App\Models\Accounting\Journal;
use App\Models\Branch;
use App\Models\Expense;
use App\Models\Group;
use App\Models\Income;
use App\Models\User;
use App\Models\UserBranch;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Intervention\Image\Facades\Image;

class Helper
{

    public static function group()
    {
        $co_id = [];
        $user  = Auth::user();
        // if ($user->type==1)
        // if ($user->roles[0]->id==1) { // Is admin
        if ($user->type==1) { // Is admin
            $co_id = User::where('status', 1)->whereIn('type',[2,3])->pluck('id')->toArray();
        }
        else if($user->type == 2){
            $co_id = User::where('id',$user->id)->pluck('id')->toArray();
        }
        else {
            $co = Group::leftJoin('users', 'users.id', '=', 'groups.user_id')
                ->where('groups.status', 1)
                ->where('users.status', 1)
                ->where('user_id', $user->id)
                ->pluck('co_id');
            if ($co->isNotEmpty()) {
                $co_id = $co->toArray();
            }
        }
        return $co_id;
    }

    public static function prefix()
    {
        $branch_id  = Auth::user()->branch_id;
        $branch_pre = Branch::where('id',$branch_id)->first();
        return $branch_pre->branch_prefix;
    }

    //***********  Client Code ***********/
    public static function codeClientAuto($model, $prefix, $print, $column)
    {
        $maxId      = null;
        $generate   = null;
        $branch     = Auth::user()->branch_id;
        $client_pre = Branch::where('id',$branch)->first();
        do {
            if ($maxId == null) {
                $maxId = $model::withTrashed()->where('branch_id',$branch)->count();
                if ($maxId>0) {
                    $generate =  '-'.$client_pre->client_prefix.sprintf("%0{$print}d", ($maxId + 1));
                } else {
                    $generate =  '-'.$client_pre->client_prefix.sprintf("%0{$print}d", 1);
                }
            } else {
                $maxId++;
                $generate =  '-'.$client_pre->client_prefix.sprintf("%0{$print}d", ($maxId + 1));
            }
        } while ($model::where($column, $generate)->exists());
        return $prefix.$generate;
    }
    //*********** CO Code ***********/
    public static function codeCOAuto($model,$prefix, $print, $column)
    {
        $maxId = null;
        $branch = Auth::user()->branch_id;
        $co_pre =  Branch::where('id',$branch)->first();
        $generate = null;
        do {
            if ($maxId == null) {
                $maxId = $model::where('branch_id',$branch)->where('type',2)->count();
                if ($maxId>0) {
                    $generate = '-'.$co_pre->co_prefix.'-'. sprintf("%0{$print}d", ($maxId + 1));
                } else {
                    $generate = '-'.$co_pre->co_prefix.'-'. sprintf("%0{$print}d", 1);
                }
            } else {
                $maxId++;
                $generate = '-'.$co_pre->co_prefix.'-'. sprintf("%0{$print}d", ($maxId + 1));
            }
        } while ($model::where($column, $generate)->exists());
        return $prefix.$generate;
    }
    //*********** User Code ***********/
    public static function codeUserAuto($model,$print,$column)
    {
        $maxId    = null;
        $branch   = Auth::user()->branch_id;
        $user_pre =  Branch::where('id',$branch)->first();
        $generate = null; 
        do {
            if ($maxId == null) {
                $maxId = $model::where('branch_id',$branch)->where('id','<>',1)->count();
                if ($maxId>0) {
                    $generate =$user_pre->user_prefix. sprintf("%0{$print}d", ($maxId + 1));
                } else {
                    $generate =$user_pre->user_prefix. sprintf("%0{$print}d", 1);
                }
            } else {
                $maxId++;
                $generate = sprintf("%0{$print}d", ($maxId + 1));
            }
        } while ($model::where($column, $generate)->exists());
        return $generate;
    }

    //*********** Loan Code ***********/
    public static function codeLoanAuto($model, $prefix, $client_code, $column,$level_loan)
    {
        $maxId = null;
        $branch = Auth::user()->branch_id;
        $loan_pre =  Branch::where('id',$branch)->first();
        $generate = null;
        $format_level = str_pad($level_loan, 2, '0', STR_PAD_LEFT);
        $sub_client_code = substr($client_code, -6);
        do {
            if ($maxId == null) {
                $maxId = $model::where('branch_id',$branch)->count();

                if ($maxId>0) {
                    $generate = '-'.$loan_pre->loan_prefix.'-'.$sub_client_code.'-'.$format_level;
                } else {
                    $generate = '-'.$loan_pre->loan_prefix.'-'.$sub_client_code.'-'.$format_level;
                }
            } else {
                $maxId++;
                $generate = '-'.$loan_pre->loan_prefix.'-'.$sub_client_code.'-'.$format_level;
            }
        } while ($model::where($column, $generate)->exists());
        return $prefix.$generate;
    }

    public static function invoiceDepreciationAuto($model, $prefix, $print, $column)
    {

        $maxId    = null;
        $generate = null;

        $branch = Auth::user()->branch_id;
        $maxId = $model::where('branch_id',$branch)->count();
        if ($maxId>0) {
            $generate = $prefix.'-'. sprintf("%0{$print}d", ($maxId + 1));
        } else {
            $generate = $prefix.'-'. sprintf("%0{$print}d", 1);
        }
        return $generate;
    }

    //*********** Invoice Payment ***********/
    public static function invoiceNumberAuto($model, $prefix, $print, $column)
    {
        $maxId    = null;
        $generate = null;
        $branch   = Auth::user()->branch_id;
        $invoice_pre =  Branch::where('id',$branch)->first();
        $maxId = $model::where('branch_id',$branch)->count();
        if ($maxId>0) {
            $generate = $prefix.'-'.$invoice_pre->invoice_prefix.'-'. sprintf("%0{$print}d", ($maxId + 1));
        } else {
            $generate = $prefix.'-'.$invoice_pre->invoice_prefix.'-'. sprintf("%0{$print}d", 1);
        }
        return $generate;
    }

    //*********** Parent ID Journals ***********/
    public static function findParentId(){
        $parent_id = Journal::max('id');
        $max = $parent_id==null?1:$parent_id;
        if($parent_id==null) {
            $parent_id = $max;
        } else {
            $parent_id =$max+1;
        }
        return $parent_id;
    }
    //*********** Parent ID Expense ***********/
    public static function findParentIdExpense(){
        $parent_id = Expense::max('id');
        $max = $parent_id==null?1:$parent_id;
        if($parent_id==null){
            $parent_id = $max;
        }
        else{
            $parent_id =$max+1;
        }
        return $parent_id;
    }
    //*********** Parent ID Income ***********/
    public static function findParentIdIncome(){
        $parent_id = Income::max('id');
        $max = $parent_id==null?1:$parent_id;
        if($parent_id==null){
            $parent_id = $max;
        }
        else{
            $parent_id =$max+1;
        }
        return $parent_id;
    }
    //*********** Branch ***********/
    public static function byBranch(){
        $log_id = Auth::id();
        $is_active_branch = Auth::user()->branch_id;
        $branches = UserBranch::select('branches.*')
            ->join('branches','branches.id','=','user_branches.branch_id')
            ->where('user_branches.user_id',$log_id)
            ->where(function($query) use ($is_active_branch){
                if($is_active_branch != -1){
                    $query->where('user_branches.branch_id',$is_active_branch);
                }
            })
            ->groupBy('user_branches.branch_id')
            ->get();
        $user_branch = [];
        foreach ($branches as $key => $value) {
            $user_branch[] = $value->id;
        }
        return $user_branch;
    }
    //*********** Currency ***********/
    public static function byCurrency(){
        $user_currency = Auth::user()->currency_id;
        return $user_currency;
    }


    public static function deleteFile($imagePath)
    {
        if (File::exists(public_path($imagePath))) {
            return File::delete(public_path($imagePath));
        }
    }

    public static function uploadFile($file, $path, $pathOldFile = '')
    {

        $timestamp    = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
        $name         = str_replace([' ', ':'], '-', $timestamp . '.' . $file->getClientOriginalName());
        $file->storeAs($path, $name);
        if ($pathOldFile != '') {
            self::deleteFile($pathOldFile);
        }
        return $path . $name;
    }

    public static function Base64Upload($stringFile, $path, $pathOldFile = '')
    {
        if ($stringFile) {
            if (!empty(explode('data:image/', $stringFile)[0])) {
                return $stringFile;
            } else {
                $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
                $name   =  rand(100000, 999999) . $timestamp . '.' . explode('/', explode(':', substr($stringFile, 0, strpos($stringFile, ";")))[1])[1];
                $img    = Image::make($stringFile);
                $img->save(public_path($path) . $name);
                $img->resize(150, 150);
                if ($pathOldFile != '') {
                    self::deleteFile($pathOldFile);
                }
                return $path . $name;
            }
        } else {
            return '';
        }
    }

    public static function sendTelegramMessage($chat_id, $message)
    {
        try {
            $response = Http::post(config("somnab.telegram.api") . config("somnab.telegram.token") . "/sendMessage", [
                "chat_id"       =>  $chat_id,
                "text"          =>  $message,
                "parse_mode"    =>  "html"
            ]);
            return $response;
        } catch (\Exception $exception) {
            dd($exception);
            return $exception->getMessage();
        }
    }

    public static function codeGenerate($model, $prefixLength = 2)
    {
        $maxId = null;
        $generate = null;
        $subfix = '';
        do {
            if ($maxId == null) {
                $maxId = $model::withTrashed()->max('id');
                if ($maxId) {
                    $generate = ($maxId + 1);
                } else {
                    $generate = "1";
                }
            } else {
                $maxId++;
                $generate = ($maxId + 1);
            }
            if (strlen($generate) == 1) {
                $subfix = '000000';
                $generate = $generate . "0";
            } else {
                $subfix = '000000';
            }
        } while ($model::withTrashed()->where('code', $generate . $subfix)->exists());
        return [
            'slug' => $generate,
            'code' => $generate . $subfix
        ];
    }

    public static function codeGenerateRelated($model, $id, $modelRelated, $idRelated, $subfix)
    {
        $maxId = null;
        $generate = null;
        $code = '';
        $slugRelated = $modelRelated::find($idRelated);
        $oldRecode =  $model::find($id);
        if ($oldRecode) {
            $generate = $slugRelated->slug .  substr($oldRecode->slug, -2);
            if ($generate != $oldRecode->slug) {
                $count = $model::withTrashed()->where("{$model::$relationforCode}", $idRelated)->count();
                $code = $slugRelated->slug .  sprintf("%02d", ($count + 1)) . $subfix;
            } else {
                $code = $oldRecode->code;
            }
        } else {
            do {
                if ($maxId == null) {
                    $maxId = $model::withTrashed()->where("{$model::$relationforCode}", $idRelated)->count();
                    if ($maxId) {
                        $generate = $slugRelated->slug .  sprintf("%02d", ($maxId + 1));
                    } else {
                        $generate = $slugRelated->slug . sprintf("%02d", 1);
                    }
                } else {
                    $maxId++;
                    $generate = $slugRelated->slug . sprintf("%02d", ($maxId + 1));
                }
                $code = $generate . $subfix;
            } while ($model::withTrashed()->where($model::$relationforCode, $idRelated)->where('code', $code)->exists());
        }
        return [
            'slug' => $generate,
            'code' => $code
        ];
    }
    public static function codeGenerateAuto($model, $prefix, $print, $column)
    {
        $maxId = null;
        $generate = null;
        do {
            if ($maxId == null) {
                $maxId = $model::max('id');
                if ($maxId) {
                    $generate = $prefix .'-'. sprintf("%0{$print}d", ($maxId + 1));
                } else {
                    $generate = $prefix .'-'. sprintf("%0{$print}d", 1);
                }
            } else {
                $maxId++;
                $generate = $prefix .'-'. sprintf("%0{$print}d", ($maxId + 1));
            }
        } while ($model::where($column, $generate)->exists());
        return $generate;
    }
}
