<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Project;
use App\Models\Settings;
use Illuminate\Support\Facades\Http;

class CheckProject
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // $project = Project::find($request->route('project'));
        // if (!$project) {
        //     return response()->json(['message' => 'Project not found'], 404);
        // }

        $setting = Settings::first();


        if ($setting && $setting->project_created == false) {
            $apiUrl = 'https://track-projects.tek-part.com/api/store';

            $response = Http::post($apiUrl, [
                'domain' => asset('/'),
                'project_name' => $setting->name['en'] ?? 'undefined',
                'project_description' => $setting->description['en'] ?? 'undefined',
                'activation_date' => now()->format('Y-m-d H:i:s'),
            ]);
            // return dd($response->json());

            $responseData = $response->json();
            // return dd($responseData);
            if (isset($responseData['date_add']) && $responseData['date_add'] === true) {
                $setting->update(['project_created' => true]);
            }
        }

        return $next($request);
    }
}
