<?php

use App\Models\Transaction;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\File;

function img($path){
    if($path){
        return asset('storage/'.$path);
    }
    return 'https://picsum.photos/300';
}

function uploadImg($file, $dir = 'logos'){
    if(!$file){
        return null;
    }
    return $file->store($dir, 'public');
}

function updateImg($file, $dir, $oldFile){
    if(!$file){
        return $oldFile;
    }

    deleteImg($oldFile);

    return uploadImg($file, $dir);
}

function deleteImg($file){
    if($file && $file != "default.jpeg"){
        if(File::exists(public_path('storage/'.$file))){
            File::delete(public_path('storage/'.$file));
        }
    }
}

function credit_balance($id, $amount, $details){
    $user = User::find($id);
    if($user){
        $user->increment('balance', $amount);
    }

    Transaction::create([
        'user_id' => $id,
        'type' => 'credit',
        'amount' => $amount,
        'details' => $details
    ]);
}
function debit_balance($id, $amount, $details){
    $user = User::find($id);
    if($user){
        if($user->balance < $amount){
            throw new Exception("Insufficient balance");
            return;
        }
        $user->balance -= $amount;
        $user->save();
    }

    Transaction::create([
        'user_id' => $id,
        'type' => 'debit',
        'amount' => $amount,
        'details' => $details
    ]);
}

function wp_msg($user){
    $settings = config('app.settings');

    $format = "Welcome To ".config('app.name');

    if($user->verified_at){
        $format .= "\n".$settings['active_id_wp_before_text'];
        $format .= "\nStudent id:".$user->id;
        $format .= "\nName:".$user->name;
        $format .= "\nPhone:".$user->phone;
        $format .= "\nJoin Date:".$user->created_at->format('d-m-Y');
        $format .= "\nActive Date:".Carbon::parse($user->verified_at)->format('d-m-Y');
        $format .= "\n".$settings['active_id_wp_after_text'];
    }
    else{
        $format .= "\n".$settings['inactive_id_wp_before_text'];
        $format .= "\nStudent id:".$user->id;
        $format .= "\nName:".$user->name;
        $format .= "\nPhone:".$user->phone;
        $format .= "\nJoin Date:".$user->created_at->format('d-m-Y');
        $format .= "\n".$settings['inactive_id_wp_after_text'];   
    }

    return urlencode($format);
}