<?php

namespace App\Http\Controllers;

use App\Models\Devis;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Facture;
use App\Models\Montant;
use App\Models\SignedUrl;
use App\Models\TypeDocument;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Image;
use LocationIP;

class CarenceController extends Controller
{

    public function create(Request $request, $dossier_id, $token)
    {

        if (!$request->hasValidSignature()) {
            abort(403);
        }
        $docs = SignedUrl::where('signature', $token)->with('typedocument')->first();
        if (!$docs) {
            abort(403);
        }

        $dossier = Dossier::whereId($dossier_id)->with('document')->firstOrFail();
        $url = URL::temporarySignedRoute(
            'Carence.store',
            now()->addMinutes(30),
            ['dossier_id' => $dossier_id, 'token' => $token]
        );

        return view('configuration.carence.make', compact('docs', 'url', 'token'));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if (!$request->hasValidSignature()) {
            abort(403);
        }

         if (isset($_SERVER['HTTP_CLIENT_IP']))
            $iprequest = $_SERVER['HTTP_CLIENT_IP'];
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $iprequest = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_X_FORWARDED']))
            $iprequest = $_SERVER['HTTP_X_FORWARDED'];
        else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
            $iprequest = $_SERVER['HTTP_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_FORWARDED']))
            $iprequest = $_SERVER['HTTP_FORWARDED'];
        else if (isset($_SERVER['REMOTE_ADDR']))
            $iprequest = $_SERVER['REMOTE_ADDR'];
        else
            $iprequest = 'UNKNOWN';
        


        $exist = SignedUrl::where('signature', $request->token)->first();
        if (!$exist) {
            abort(403);
        }
        $data = LocationIP::get($iprequest);
        $dossier = Dossier::whereId($exist->dossier_id)->firstOrFail();
        $montant = Montant::where('dossier_id', $dossier->id)->first();
        $types = TypeDocument::all();
        foreach ($types as $type) {
            $t = str_replace(" ", "_", $type->type);

            if ($request->file($t)) {
                // dd($request->file($t));
                if ($type->id == 4) {
                    $deviscount = Devis::where('dossier_id', $dossier->id)->count();
                    $numdevis = $deviscount + 1;
                    $devis = Devis::create([
                        'montant_devis' => $request->montant_devis,
                        'dossier_id' => $dossier->id,
                        'devis_status_id' => 4,
                        'devis' => $numdevis,
                        'date_reception' => now()
                    ]);
                    Montant::updateOrCreate(['dossier_id' => $dossier->id], [
                        'devis_id' => $devis->id,
                    ]);
                }
                if ($type->id == 8) {
                    $facturecount = Facture::where('dossier_id', $dossier->id)->count();
                    $c =  $facturecount + 1;
                    $facture = Facture::create([
                        'montant_facture' => $request->montant_facture,
                        'dossier_id' => $dossier->id,
                        'devis_status_id' => 4,
                        'facture' => $c,
                        'date_reception' => now()

                    ]);
                    Montant::updateOrCreate(['dossier_id' => $dossier->id], [
                        'facture_id' => $facture->id,
                    ]);
                }

                $files = $request->file($t);
                foreach ($files as $file) {
                    if ($file->getClientMimeType() === 'application/pdf') {
                    } else {
                        if ($data) {
                            $text = 'lat:' . $data->latitude ?? null . 'long:' . $data->longitude . '/' . $data->regionName ?? null . '/date :' . now();
                        } else {
                            $text = 'date :' . now();
                        }
                        $img = Image::make($file);
                        $watermark = Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(70);
                        $img->insert($watermark, 'center', 10, 10);

                        $img->text($text, $img->width() - 100, $img->height() - 100, function ($font) {
                            $font->file(public_path('fonts/gnuolane.ttf'));
                            $font->size(25);
                            $font->color('#0004fa');
                            $font->align('right');
                            $font->valign('bottom');
                            $font->angle(0);
                        });
                        $filename = uniqid() . '.' . 'png';
                        Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                        $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                        // Store the file in the disk
                        $doc = Document::create([
                            'path' => $path3,
                            'type_document_id' => $type->id,
                            'dossier_id' => $dossier->id,
                        ]);
                        if ($type->id == 4) {
                            $devis->document()->attach($doc->id);
                        } else if ($type->id == 8) {
                            $facture->document()->attach($doc->id);
                        }
                    }
                }
            }
        }

        if ($request->pdf) {
            $array = explode(",", $request->pdf);
            for ($i = 0; $i < count($array); $i += 3) {

                $image = base64_decode($array[$i + 1]);
                $filename = uniqid() . '.' . 'png';
                $text = 'lat:'.$data->latitude.'long:'.$data->longitude.'/'.$data->regionName.'/date :'.now();
                $img = Image::make($image);
                $watermark = Image::make(public_path('/img/png.png'))->resize(100, 120)->opacity(70);
                $img->insert($watermark, 'center', 10, 10);
                $img->text($text , $img->width() - 230 , $img->height() - 100, function ($font) {
                    $font->file(public_path('fonts/gnuolane.ttf'));
                    $font->size(26);
                    $font->color('#0004fa');
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(0);
                });
                Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                Document::create([
                    'path' => $path,
                    'dossier_id' => $dossier->id,
                    'type_document_id' => $array[$i + 2]
                ]);

                if ($array[$i + 1] == 4) {
                    $devis->document()->attach($doc->id);
                }
                if ($array[$i + 1] == 8) {
                    $facture->document()->attach($doc->id);
                }
            }
        }

        $exist->delete();


        return view('success');

    }
}
