<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\ContractRequest;
use App\Models\Document\DocumentType;
use App\Models\KeyDate;
use App\Services\HistoryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class EsignWebhookController extends Controller
{
    public function input(Request $request, HistoryService $history) {
        $data = $request->all();

        Log::debug("Webhook Data", $data);

        $cr = ContractRequest::where('slug', $data['external_id'])->first();

        if(!$cr) {
            return response()->json(['error' => 'Not found'], 404);
        }

        $client = $cr->client;
        $receivedDocuments = [];

        foreach ($data['documents'] as $document) {

            $fileName = $document['document_name'];
            $url      = $document['url'];

            $unsluggedName = Str::of($fileName)
                ->replace(['-', '_'], ' ')
                ->title()
                ->toString();

            $docType = DocumentType::where('display_name', $unsluggedName)->first();

            $displayName = $docType?->display_name ?? $unsluggedName;
            $typeId      = $docType?->id;

            $response = Http::get($url);

            if (!$response->successful()) {
                continue;
            }

            $directory = $client->getDocumentStoragePath();
            $path      = $directory . basename($url);

            Storage::put($path, $response->body());

            $fullPath = Storage::path($path);

            $doc = $client->documents()->create([
                'solicitor_id' => $client->solicitor_id,
                'user_id'      => null,
                'display_name' => "Signed {$displayName}",
                'file_name'    => basename($url),
                'file_type'    => File::extension($fullPath),
                'file_size'    => filesize($fullPath),
                'type_id'      => $typeId,
            ]);

            $receivedDocuments[] = [
                'document_id' => $doc->id,
                'name' => "Signed {$displayName}",
            ];

            if($fileName == 'cfa') {
                $client->claim->keyDates()->syncWithoutDetaching([
                    23 => ['date' => date('Y-m-d')],
                    24 => ['date' => date('Y-m-d', strtotime('+14 day'))],
                ]);
            }
        }

        if (!empty($receivedDocuments)) {
            $history->add($client, 'Signed document(s) received via e-signature webhook.', [
                'contract_request_id' => $cr->id,
                'documents' => $receivedDocuments,
            ]);
        }

        return response()->json(['status' => 'success'], 200);
    }
}