<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Route;
use App\Models\Client;
use App\Models\Company;
use App\Models\CompanyClient;
use App\Models\Pro;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

use App\Models\InternalMessage;
use OpenTok\MediaMode;
use OpenTok\OpenTok;
use Ramsey\Collection\CollectionInterface;

class MessageController extends Controller
{
    protected $opentok;
    protected $otSession;
    protected $otSessionId;
    protected $otToken;


    public function __construct(Request $request)
    {
        parent::__construct();

        $this->opentok = new OpenTok(config('app.opentokApiKey'),config('app.opentokApiSecret'));
        $this->otSession = $this->opentok->createSession(array('mediaMode' => MediaMode::ROUTED));
        $this->otSessionId = $this->otSession->getSessionId();
        $this->otToken = $this->opentok->generateToken($this->otSessionId);

        view()->share('opentok',$this->opentok);
        view()->share('otSession',$this->otSession);
        view()->share('otSessionId',$this->otSessionId);
        view()->share('otToken',$this->otToken);
    }

    public function messages(Request $request, Client $patient){
        $defaultCompanyClient = $this->getDefaultCompanyClientFromSession($patient);
        $defaultCompany = $defaultCompanyClient->company;
        $regardingClient = $patient;
        $messages = InternalMessage::where('regarding_company_id', $defaultCompany->id)->where('regarding_client_id', $patient->id)->orderBy('created_at', 'ASC')->paginate(100);

        return view('app.patient.company-client.messages', compact('patient', 'regardingClient', 'messages', 'defaultCompanyClient', 'defaultCompany'));
    }

    public function clientMessagesAttachments(Request $request, Client $patient, InternalMessage $message)
    {
        if(!$message) return '';
        $output = [];
        foreach ($message->attachments as $attachment) {
            $output[] = '<a native target="_blank" ' .
                'href="/api/internalMessageAttachment/download/' . $attachment->uid . '" ' .
                'class="attachment text-sm my-1">' .
                '<i class="fa fa-paperclip"></i>&nbsp;' .
                $attachment->systemFile->file_name .
                '</a>';
        }
        return implode("", $output);
    }

}
