<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
// use App\DataTables\ContabilitaDataTableEditor;
use App\DataTables\IssueDataTable;
use App\Models\Issue;
use App\Models\User;
use App\Models\Config;
use Carbon\Carbon;
use PDF;
use Storage;
use Session;

class IssueController extends Controller
{
  public function index(IssueDataTable $dataTable){
    $collection = Issue::getCollection();

    return $dataTable->with(['issues' => $collection])->render('issue.index');
  }

  public function show(Request $request){
    $redmineUser = session('redmine_user');

    $response_issue = Http::get(session('azienda')->redmine_url.'/issues/'.$request->issue_id.'.json?include=attachments,relations', [
      'key' => $redmineUser->api_key,
    ]);

    $response_helpesk = Http::get(session('azienda')->redmine_url.'/helpdesk_tickets/'.$request->issue_id.'.json', [
      'key' => $redmineUser->api_key,
    ]);


    if($response_issue->ok()){
      $issue = $response_issue->object()->issue;

      try{
        $helpdesk = $response_helpesk->object()->helpdesk_ticket;
        $author = $helpdesk->contact->name." (".$helpdesk->from_address.")";
      }catch(\Exception $e){
        $author = $issue->author->name;
      }

      // if($response_helpesk->ok() && property_exists($helpdesk, 'contact')){
      // }else{
      // }

      return view('issue.show')->with(['issue' => $issue, 'author' => $author]);
    }else{
      Session::flash('flash_message', "Errore generico");
      dd($response_issue->object());
      return redirect()->route('home');
    }
  }

  public function firma($id){
    $redmineUser = session('redmine_user');

    // Issue details
    $response_issue = Http::get(session('azienda')->redmine_url.'/issues/'.$id.'.json?include=attachments,relations,custom_fields', [
      'key' => $redmineUser->api_key,
    ]);
    $issue = $response_issue->object()->issue;

    // Sede del cliente
    $sedeCliente = null;
    try{
      foreach($issue->custom_fields as $custom_field){
        if(str_starts_with($custom_field->name, 'Sede')){
          $sedeCliente = $custom_field->value;
          break;
        }
      }
    }catch(\Exception $e){
      $sedeCliente = null;
    }

    // Activity
    $attivita = Issue::getAttivita();

    // issueStatus
    $issueStatus = Issue::getStati();

    // Altri tecnici
    $response = Http::get(session('azienda')->redmine_url.'/projects/'.$issue->project->id.'/memberships.json', [
      'key' => $redmineUser->api_key,
    ]);

    $memberships = $response->object()->memberships;
    $altriTecnici = array();

    try{
      foreach($memberships as $membership){
        if($membership->user->id == $redmineUser->id) continue; // Scarto il tecnico attualmente loggato
        $altriTecnici[$membership->user->id] = $membership->user->name;
      }
    }catch(\Exception $e){
    }

    // Altre segnalazioni dello stesso progetto, da associare come sottoattività
    $altreSegnalazioni = Http::get(session('azienda')->redmine_url.'/issues.json', [
      'key' => $redmineUser->api_key,
      'project_id' => $issue->project->id
    ]);

    $collectionAltreSegnalazioni = new Collection();

    foreach($altreSegnalazioni->object()->issues as $issueCorrelato){
      $collectionAltreSegnalazioni->push($issueCorrelato);
    }

    // foreach($collectionAltreSegnalazioni as $t){
    //   dd($t->status);
    // }

    $user = User::where('redmine_id', $redmineUser->id)->first();



    return view('issue.firma')->with([
      'issue' => $issue,
      'attivita' => $attivita,
      'issueStatus' => $issueStatus,
      'altriTecnici' => $altriTecnici,
      'altreSegnalazioni' => $collectionAltreSegnalazioni,
      'user' => $user,
      'sedeCliente' => $sedeCliente
    ]);
  }

  public function firma_rapporto(Request $request){

    // Controllo orari e durata intervento
    try{
      $inizio = Carbon::createFromFormat('H:i', $request->ora_inizio);
      $fine = Carbon::createFromFormat('H:i', $request->ora_fine);
      $durata = $fine->diffInMinutes($inizio);
      $orePausa = floatval($request->ore_pausa);
      if($orePausa > 0){
        $minutiPausa = 60*$orePausa;
        $durata -= $minutiPausa;
      }

      if($durata <= 0){
        return back()->withErrors(['msg' => 'La durata complessiva dell\'intervento non deve essere minore di 0. Controlla orario di inizio, fine e pausa']);
      }
    }catch(\Exception $e){
      return back()->withErrors(['msg' => 'Orari non validi']);
    }



    $redmineUser = session('redmine_user');
    $user = User::where('redmine_id', $redmineUser->id)->first();

    $response_issue = Http::get(session('azienda')->redmine_url.'/issues/'.$request->issue_id.'.json?include=attachments,relations', [
      'key' => $redmineUser->api_key,
    ]);
    $issue = $response_issue->object()->issue;

    // $response_helpesk = Http::get(session('azienda')->redmine_url.'/helpdesk_tickets/'.$request->issue_id.'.json', [
    //   'key' => $redmineUser->api_key,
    // ]);
    // $helpdesk = $response_helpesk->object()->helpdesk_ticket;

    // Cliente
    $cliente = $issue->project->name;

    $dataIntervento = Carbon::createFromFormat('d/m/Y', $request->spent_on);

    // Array dei tecnici presenti
    $tecnici = array();
    $tecnici[$redmineUser->id] = $redmineUser->firstname." ".$redmineUser->lastname;

    if($request->has('altro_tecnico')){
      foreach($request->altro_tecnico as $key => $value){
        $tecnici[$key] = $value;
      }
    }

    // Firme
    $sign_path_cliente = 'sign_cliente_'.time().'.png';
    if($request->has('signature_image_cliente')){
      $encoded_image = explode(",", $request->signature_image_cliente)[1];
      $sign_cliente = base64_decode($encoded_image);
    }

    // Genero il PDF
    // return view('issue.pdf', [
    //   'issue' => $issue,
    //   'dataIntervento' => $dataIntervento,
    //   'note' => $request->note,
    //   'firmaTecnico' => $sign_tecnico,
    //   'firmaCliente' => $sign_cliente,
    //   'materiale_utilizzato' => $request->materiale_utilizzato,
    //   'merce_ritirata' => $request->merce_ritirata,
    //   'merce_consegnata' => $request->merce_consegnata,
    //   'tecnici' => $tecnici,
    //   'inizio' => $inizio,
    //   'fine' => $fine,
    //   'persona_riferimento' => $request->persona_riferimento,
    //   'cliente' => $cliente
    // ]);
    $hours = floor($durata / 60);
    $minutes = ($durata % 60);

    $pdf = PDF::loadView('issue.pdf', [
      'issue' => $issue,
      'dataIntervento' => $dataIntervento,
      'note' => $request->note,
      'firmaCliente' => $sign_cliente,
      'materiale_utilizzato' => $request->materiale_utilizzato,
      'merce_ritirata' => $request->merce_ritirata,
      'merce_consegnata' => $request->merce_consegnata,
      'tecnici' => $tecnici,
      'inizio' => $inizio,
      'fine' => $fine,
      'persona_riferimento' => $request->persona_riferimento,
      'cliente' => $cliente,
      'user' => $user,
      'sedeCliente' => $request->sedeCliente,
      'durata' => $hours.'h '.$minutes.'min'
    ]);

    $folder_name = Storage::disk('temp')->getDriver()->getAdapter()->getPathPrefix();
    $pdf->save($folder_name."/issue_".$request->issue_id.".pdf");
    // return $pdf->stream();

    $uploads = array();

    // Upload del file pdf firmato
    $filename = 'rapporto_'.$request->issue_id."_".time().".pdf";
    $response = Http::withHeaders([
      'content-type' => 'application/octet-stream'
    ])
    ->withBody($pdf->output(), 'application/pdf')
    ->post("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/uploads.json', [
      'filename' => $filename
    ]);

    // dd($response->object());


    $uploadToken = $response->object()->upload->token;
    $uploads[] = [
      'token' => $uploadToken,
      'filename' => $filename,
      'description' => "Rapporto d'intervento firmato",
      'content_type' => 'application/pdf'
    ];

    // Upload degli allegati
    if($request->hasFile('allegato')){
      foreach($request->allegato as $allegato){
        $exploded = explode(".", $allegato->getClientOriginalName());
        $originalFilename = "";
        if(count($exploded) > 1){
          $index = count($exploded) - 2;
          $exploded[count($exploded)-1] = ".".$allegato->extension();
        }else{
          $index = 0;
        }
        $exploded[$index] .= '_'.time();

        $originalFilename = implode($exploded);

        $response = Http::withHeaders([
          'content-type' => 'application/octet-stream'
        ])
        ->withBody($allegato->get(), $allegato->getMimeType())
        ->post("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/uploads.json', [
          'filename' => $originalFilename
        ]);

        // $response->throw(function ($response, $e) {
        //   dd($response->body());
        // });

        $uploadToken = $response->object()->upload->token;
        $uploads[] = [
          'token' => $uploadToken,
          'filename' => $originalFilename,
          'description' => $originalFilename,
          'content_type' => $allegato->getMimeType()
        ];

      }
    }



    // Elimino le firme
    Storage::disk('temp')->delete([$sign_path_cliente]);

    // Aggiorno lo issue
    $response = Http::acceptJson()->put("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/issues/'.$request->issue_id.'.xml', [
      'issue' => [
        'notes' => $request->note,
        'status_id' => $request->status_id,
        'uploads' => $uploads
      ],
      'helpdesk' => [
        'is_send_mail' => 1
      ],
    ]);

    $response->throw(function ($response, $e) {
      dd($e);
      Session::flash('flash_message', "Errore nell'update dell'issue");
      return redirect()->route('home');
    });

    // Time entry
    foreach($tecnici as $key => $value){
      // ore intervento
      if($key == $redmineUser->id){
        $activity_id = $request->activity_id;
      }else{
        $activity_id = Config::getValue(Config::ATTIVITA_TECNICO_AGGIUNTIVO);
      }

      $response = Http::post("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/time_entries.xml', [
        'time_entry' => [
          'issue_id' => $request->issue_id,
          'spent_on' => $dataIntervento->toDateString(),
          'hours' => $durata.'m',
          'comments' => $request->note,
          'activity_id' => $activity_id,
          'user_id' => $key,
          'custom_fields' => [
            [
              'id' => 71,
              'value' => $inizio->format('H:i')
            ],
            [
              'id' => 72,
              'value' => $fine->format('H:i')
            ]
          ]
        ]
      ]);

      // Ore viaggio
      if($request->has('ore_viaggio') && is_numeric($request->ore_viaggio)){
        $response = Http::post("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/time_entries.xml', [
          'time_entry' => [
            'issue_id' => $request->issue_id,
            'spent_on' => $dataIntervento->toDateString(),
            'hours' => $request->ore_viaggio,
            'comments' => '',
            'activity_id' => Config::getValue(Config::ATTIVITA_VIAGGIO),
            'user_id' => $key,
            'custom_fields' => [
              [
                'id' => 5,
                'value' => 'Viaggio' // Campo Custom fatturare
              ]
            ]

          ]
        ]);

      }
    }


    if($request->has('segnalazioneCorrelata')){
      // Aggiorno le relazioni

      foreach($request->segnalazioneCorrelata as $key => $segnalazioneCorrelata){
        $response = Http::post("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/issues/'.$request->issue_id.'/relations.xml', [
          'relation' => [
            'issue_to_id' => $segnalazioneCorrelata
          ]
        ]);

        // $response->throw(function ($response, $e) {
        //   dd($response);
        // });

        // Aggiorno lo stato del ticket correlato
        $response = Http::acceptJson()->put("https://".$redmineUser->api_key."@".session('azienda')->redmine_url.'/issues/'.$segnalazioneCorrelata.'.xml', [
          'issue' => [
            'status_id' => $request->segnalazioneCorrelataStatus[$segnalazioneCorrelata],
          ]
        ]);

        // $response->throw(function ($response, $e) {
        //   dd($response);
        // });
      }
    }


    // Session::flash('flash_message', "Issue aggiornato correttamente!");
    $request->session()->put('success_issue_id', $request->issue_id);
    return redirect()->route('issue.success');
  }

  public function success(Request $request){
    $success_issue_id = session('success_issue_id');
    if($success_issue_id != null){
      $request->session()->forget('success_issue_id');
      return view('issue.success')->with(['issue_id' => $success_issue_id]);
    }else{
      return redirect()->route('home');
    }
  }
}
