<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\ContractRequest;
use App\Models\Document\DocumentType;
use App\Models\KeyDate;
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) {
        $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);
        }

        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 = $cr->client->getDocumentStoragePath();
            $path      = $directory . basename($url);

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

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

            $cr->client->documents()->create([
                'solicitor_id' => $cr->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,
            ]);

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

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