<?php

namespace Mtc\Plugins\Wisebee\Classes\Handlers;

use Mtc\Plugins\Wisebee\Classes\Models\WisebeeConsultation;
use Mtc\Plugins\Wisebee\Classes\Models\WisebeeDocument;
use Wisebee\Resources\Document as RemoteDocument;

class DocumentHandler extends BaseHandler
{
    const RESOURCE_NAME = 'document';

    /**
     * Pulls documents associated with consultation and stores files on server
     *
     * @param $remoteConsultationID
     */
    public function pullDocuments($remoteConsultationID): void
    {
        $fullPath = $_SERVER['DOCUMENT_ROOT'] . WisebeeDocument::FILE_PATH;
        if (!is_dir($fullPath)) {
            mkdir($fullPath, 0770);
        }

        $wisebeeDocuments = $this->wisebee->list(RemoteDocument::class, [
            'documentable_type' => 'consultation',
            'documentable_id' => $remoteConsultationID,
            'pdf' => true,
        ]);

        $this->deleteConsultationDocuments($remoteConsultationID);

        foreach ($wisebeeDocuments as $wisebeeDocument) {
            $uriParts = explode('/', $wisebeeDocument->pdf_file);
            $fileName = end($uriParts);
            file_put_contents($fullPath . $fileName, file_get_contents($wisebeeDocument->pdf_file));

            /** @var WisebeeConsultation $wisebeeConsultation */
            $wisebeeConsultation = WisebeeConsultation::query()
                ->where('wisebee_id', $remoteConsultationID)
                ->first();
            if (empty($wisebeeConsultation)) {
                continue;
            }

            WisebeeDocument::query()
                ->create([
                    'wisebee_id' => $wisebeeDocument->id,
                    'consultation_id' => $wisebeeConsultation->id,
                    'documentable_id' => $remoteConsultationID,
                    'documentable_type' => 'consultation',
                    'title' => $wisebeeDocument->title,
                    'status' => WisebeeDocument::STATUS_NEW,
                    'file' => WisebeeDocument::FILE_PATH . $fileName,
                    'pages' => collect($wisebeeDocument->pages)->pluck('content'),
                ]);
        }
    }

    /**
     * Deletes consultation documents and files
     *
     * @param $wisebeeConsultationID
     */
    public function deleteConsultationDocuments($wisebeeConsultationID): void
    {
        $documents = WisebeeDocument::query()
            ->where([
                'documentable_type' => 'consultation',
                'documentable_id' => $wisebeeConsultationID,
            ])
            ->get();
        foreach ($documents as $document) {
            $filePath = $_SERVER['DOCUMENT_ROOT'] . $document->file;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        WisebeeDocument::query()
            ->whereIn('id', $documents->pluck('id'))
            ->delete();
    }
}