<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\CompanyMeta;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DashboardController extends Controller
{
    public function dashboard()
    {
        $tickets =  get_current_company_tickets(['type' => 'inbox']);
        $companyId = getSelectedCompany();
        $tags = getCompanyTags($companyId);
        $canned_response = $this->get_canned_responses();
        return view('index', ['tickets' => $tickets, 'tags' => $tags, 'canned_response' => $canned_response]);
    }
    
    public function get_canned_responses(){
         $companyId = getSelectedCompany();
        return  CompanyMeta::where('company_id', $companyId)->where('key', 'canned_responses')->get();
    }
    
    public function profile()
    {
        $company = getSelectedCompany();
        $user = Auth::user();
        $users = $users = User::where('role_id', '!=', 1)
            //->where('id', '!=', Auth::id())
            ->join('company_users', 'users.id', '=', 'company_users.user_id')
            ->where('company_users.company_id', $company)
            ->select('users.*')
            ->get();
        return view('profile', ['users' => $users, 'user' => $user]);
    }
    
    public function updateProfile(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'profile_image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);
        
        $user = Auth::user();
        
        if($request->hasFile('profile_image')) {
            
            //Remove Old Image
            if ($user->profile_image) {
                $oldImagePath = str_replace('/storage/', '', $user->profile_image);
                Storage::disk('public')->delete($oldImagePath);
            }
            
            //Store New Image
            $file = $request->file('profile_image');
            $extension = $file->getClientOriginalExtension();
            $filename = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $extension;
            $path = $file->storeAs('profile_images', $filename, 'public');
            
            $user->profile_image = Storage::url($path);
        }
        
        //update user
        $user->name = $request->name;
        $user->save();
        
        return back()->with('success', 'Profile Updated Successfully');
    }
}
