<?php

use App\Setting;
use App\Post;
use Illuminate\Support\Facades\Auth;
/**
 * upload file
 *
 *
 * @param $request
 * @param $name
 * @param string $destination
 * @return string
 */
function uploadFile($request, $name, $destination = '')
{
    $image = $request->file($name);

    $name = time().'.'.$image->getClientOriginalExtension();

    if($destination == '') {
        $destination = public_path('/uploads');
    }

    $image->move($destination, $name);

    return $name;
}


/**
 * add setting key and value
 *
 *
 * @param $key
 * @param $value
 * @return Setting|bool
 */
function addSetting($key, $value)
{
    if(Setting::where('setting_key', $key)->first() != null)
        return false;

    $setting = new Setting();

    $setting->setting_key = $key;

    $setting->setting_value = $value;

    $setting->save();

    return $setting;
}

/**
 * get setting value by key
 *
 * @param $key
 * @return mixed
 */
function getSetting($key)
{
    return ($setting = Setting::where('setting_key', $key)->first()) != null ? $setting->setting_value:null;
}


/**
 * check directory exists and try to create it
 *
 *
 * @param $directory
 */
function checkDirectory($directory)
{
    try {
        if (!file_exists(public_path('uploads/' . $directory))) {
            mkdir(public_path('uploads/' . $directory));

            chmod(public_path('uploads/' . $directory), 0755);
        }
    } catch (\Exception $e) {
        die($e->getMessage());
    }
}


/**
 * check if user has permission
 *
 *
 * @param $permission
 * @return bool
 */
function user_can($permission)
{
    return \Auth::user()->is_admin == 1 || \Auth::user()->can($permission);
}


/**
 * get Unread Messages
 *
 *
 * @return mixed
 */
function getUnreadMessages()
{
    $folder = \App\MailboxFolder::where('title', "Inbox")->first();

    $messages = \App\Mailbox::join('mailbox_receiver', 'mailbox_receiver.mailbox_id', '=', 'mailbox.id')
        ->join('mailbox_user_folder', 'mailbox_user_folder.user_id', '=', 'mailbox_receiver.receiver_id')
        ->join('mailbox_flags', 'mailbox_flags.user_id', '=', 'mailbox_user_folder.user_id')
        ->where('mailbox_receiver.receiver_id', \Auth::user()->id)
//                          ->where('parent_id', 0)
        ->where('mailbox_flags.is_unread', 1)
        ->where('mailbox_user_folder.folder_id', $folder->id)
        ->where('sender_id', '!=', \Auth::user()->id)
        ->whereRaw('mailbox.id=mailbox_receiver.mailbox_id')
        ->whereRaw('mailbox.id=mailbox_flags.mailbox_id')
        ->whereRaw('mailbox.id=mailbox_user_folder.mailbox_id')
        ->select(["*", "mailbox.id as id"])
        ->get();

    return $messages;
}


/**
 * getContacts
 *
 *
 * @param null $status
 * @return \Illuminate\Database\Eloquent\Collection|static[]
 */
function getContacts($status = null)
{
    if(!$status)
        return \App\Contact::all();

    return \App\Contact::join('contact_status', 'contact_status.id', '=', 'contact.status')
        ->where('contact_status.name', $status)
        ->get();

}


/**
 * get Users
 *
 *
 * @return mixed
 */
function getUsers()
{
    return \App\User::where('is_admin', 0)->where('is_active', 1)->get();
}

/**
 * get Unread Messages
 *
 *
 * @return mixed
 */
function getAdminUnreadMessages()
{
    return \App\Post::where('is_read_admin', 0)->latest()->take(10)->get();
}


/**
 * get Unread Messages
 *
 *
 * @return mixed
 */
function getStudentUnreadMessages()
{
    return \App\Post::where([
        ['is_read', 0],
        ['user_id', Auth::user()->id]
    ])->get();
}

/**
 * Log system activity
 *
 * @param string $logName Category/channel of log (e.g. 'auth', 'result', 'post', 'security')
 * @param string $description Human-readable description of event
 * @param mixed $subject Optional subject model or identifier
 * @param array $properties Additional properties (IP, user agent, metadata)
 * @return \App\ActivityLog|null
 */
function logActivity($logName, $description, $subject = null, array $properties = [])
{
    try {
        $user = Auth::check() ? Auth::user() : null;
        
        $defaultProps = [
            'ip' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'url' => request()->fullUrl(),
        ];

        return \App\ActivityLog::create([
            'log_name' => $logName,
            'description' => $description,
            'subject_id' => is_object($subject) && isset($subject->id) ? $subject->id : (is_numeric($subject) ? $subject : null),
            'subject_type' => is_object($subject) ? get_class($subject) : null,
            'causer_id' => $user ? $user->id : null,
            'causer_type' => $user ? get_class($user) : null,
            'properties' => array_merge($defaultProps, $properties),
        ]);
    } catch (\Exception $e) {
        \Illuminate\Support\Facades\Log::error('Failed to write activity log: ' . $e->getMessage());
        return null;
    }
}
