<?php

function getFileData($file, $preserveQuality = false) {
  if (!$file) return null;
  $data = [
    'modified' => $file->modified('YYYY-MM-dd'),
    'url' => $preserveQuality ? $file->thumb([
        'format' => 'webp'
    ])->url() : $file->thumb([
      'width'   => 1000,
      'quality' => 80,
      'format' => 'webp'
    ])->url(),
    'source' => $file->url(),
    'parent' => [
      "title" => (string) $file->parent()->title(),
      "uri" => $file->parent()->uri()
    ],
    'uuid' => (string) $file->uuid(),
    'name' => $file->filename(),
    'label' => (string) $file->label(),
    'type' => (string) $file->type(),
    'cover' => $file->cover()->isNotEmpty() ? $file->cover()->toFile()->thumb([
      'width'   => 1000,
      'quality' => 80,
      'format' => 'webp'
    ])->url() : null
  ];

  if ($file->description()->exists()) {
    $data['description'] = $file->description()->value();
    $data['tags'] = $file->tags()->split();
  };

  if ($file->comments()->exists()) {
    $data['comments'] = $file->comments()->exists() && $file->comments() ? Data::decode($file->comments()->value(), 'yaml') : [];
    $data['cover'] = $file->cover()->exists() && $file->cover()->isNotEmpty() ? $file->cover()->toFile()->resize(576)->url() : false;
  }

  return $data;
}

function getGlobalEvaluation($numberedGrade) {

    $DTLPage = page('design-to-light');
    $DTLGrades = $DTLPage->grades()->toStructure();

    $gradeMapping = [
        [0, 2, "E", $DTLGrades->findBy("letter", "E")->mention()->value(), $DTLGrades->findBy("letter", "E")->comment()->value()],
        [2, 4, "D", $DTLGrades->findBy("letter", "D")->mention()->value(), $DTLGrades->findBy("letter", "D")->comment()->value()],
        [4, 6, "C", $DTLGrades->findBy("letter", "C")->mention()->value(), $DTLGrades->findBy("letter", "C")->comment()->value()],
        [6, 8, "B", $DTLGrades->findBy("letter", "B")->mention()->value(), $DTLGrades->findBy("letter", "B")->comment()->value()],
        [8, 11, "A", $DTLGrades->findBy("letter", "A")->mention()->value(), $DTLGrades->findBy("letter", "A")->comment()->value()],
    ];

    foreach ($gradeMapping as [$min, $max, $letter, $mention, $comment]) {
        if ($numberedGrade >= $min && $numberedGrade < $max) {
            return [
                "letter" => $letter,
                "number" => $numberedGrade,
                "mention" => $mention,
                "comment" => $comment,
            ];
        }
    }

    return [
        "letter" => "",
        "number" => $numberedGrade,
        "mention" => "Non défini",
        "comment" => "Pas d'évaluation disponible",
    ];
}

function processDTLProposals($page) {
  $proposals = [];

  foreach ($page->dtlProposals()->toStructure() as $proposal) {
      $location = $proposal->DTLProposalLocation()->value();
      $DTLProposal = null;

      switch ($location) {
        case 'proposal':
            $proposalPage = $page->find('proposal');
            $proposalFile = $proposal->DTLproposal()->toFile();

            if ($proposalPage && $proposalFile) {
                $index = $proposalPage->pdf()->toFiles()->indexOf($proposalFile);
                $DTLProposal = [
                "title" => $proposal->DTLProposalTitle()->isNotEmpty() ? (string) $proposal->DTLProposalTitle() : null,
                "location" => [
                        "step" => "proposal",
                        "source" => (string) $proposalFile->url()
                    ],
                "path" => "/projects/" . $page->slug() . "?dialog=proposal&fileIndex=" . $index,
                "date" => $proposalFile->modified("d/MM/Y"),
                "stepLabel" => "Proposition commerciale",
                ];
            }
        break;

        case 'industrialIdeation':
            $proposalPage = $page->find('industrial-ideation');
            $proposalFile = $proposal->DTLindustrialIdeation()->toFile();

            if ($proposalPage && $proposalFile) {
                $DTLProposal = [
                "title" => $proposal->DTLProposalTitle()->isNotEmpty() ? (string) $proposal->DTLProposalTitle() : null,
                    "location" => [
                        "step" => "industrialIdeation",
                        "source" => (string) $proposalFile->url()
                    ],
                    "path" => "/projects/" . $page->slug() . "?dialog=industrial-ideation",
                    "date" => $proposalFile->modified("d/MM/Y"),
                    "stepLabel" => "Idéation industrielle",
                ];
            }
        break;

        case 'virtualSampleDynamicTrack':
            $proposalPage = $proposal->DTLVirtualSampleDynamicTrack()->toPage();
            if ($proposalPage) {
                $DTLProposal = [
                "title" => $proposal->DTLProposalTitle()->isNotEmpty() ? (string) $proposal->DTLProposalTitle() : null,
                    "location" => [
                        "step" => "virtualSample",
                        "type" => "dynamic",
                        "trackSlug" => (string) $proposalPage->slug()
                    ],
                    "path" => "/projects/" . $page->slug() . "?dialog=virtual-sample",
                    "date" => $proposalPage->modified("d/MM/Y"),
                    "stepLabel" => "Échantillon virtuel - piste dynamique",
                ];
            }
        break;

        case 'virtualSampleStaticTrack':
            $proposalPage = $page->find('virtual-sample');
            $proposalFile = $proposal->DTLVirtualSampleStaticTrack()->toFile();
            if ($proposalPage && $proposalFile) {
                $DTLProposal = [
                "title" => $proposal->DTLProposalTitle()->isNotEmpty() ? (string) $proposal->DTLProposalTitle() : null,
                    "location" => [
                        "step" => "virtualSample",
                        "type" => "static",
                        "source" => (string) $proposalFile->url()
                    ],
                    "path" => "/projects/" . $page->slug() . "?dialog=virtual-sample",
                    "date" => $proposalFile->modified("d/MM/Y"),
                    "stepLabel" => "Échantillon virtuel - piste statique",
                ];
            }
        break;
      }

      if ($DTLProposal) {            
          if (isset($proposalFile) && $proposalFile->cover()->isNotEmpty()) {                
              $DTLProposal["thumb"] = $proposalFile->cover()->toFile()->thumb([
                  "width" => 200,
                  "format" => "webp"
              ])->url();
          }
          if ($proposalPage->views()->isNotEmpty()) {
              $DTLProposal["thumb"] = $proposalPage->views()->toFile()->thumb([
                  "width" => 200,
                  "format" => "webp"
              ])->url();
          }

          $numberedGlobalGrade = (int) $proposal->DTLGrade()->value() ?? 0;

          $DTLProposal["grades"] = [
              "global" => getGlobalEvaluation($numberedGlobalGrade),
              "position" => [
                  "complexity" => (int) $proposal->DTLComplexityGrade()->value() ?? 0,
                  "weight" => (int) $proposal->DTLWeightGrade()->value() ?? 0,
              ],
              "indicators" => [
                  [
                      "id" => "design",
                      "label" => "Design Global",
                      "value" => (int) $proposal->DTLDesignGrade()->value() ?? 0,
                  ],
                  [
                      "id" => "ring",
                      "label" => "Bague",
                      "value" => (int) $proposal->DTLRingGrade()->value() ?? 0,
                  ],
                  [
                      "id" => "shoulder",
                      "label" => "Épaule",
                      "value" => (int) $proposal->DTLShoulderGrade()->value() ?? 0,
                  ],
                  [
                      "id" => "skeleton",
                      "label" => "Colonnes & Arêtes",
                      "value" => (int) $proposal->DTLSkeletonGrade()->value() ?? 0,
                  ],
                  [
                      "id" => "foot",
                      "label" => "Pied",
                      "value" => (int) $proposal->DTLFootGrade()->value() ?? 0,
                  ],
                  [
                      "id" => "bottom",
                      "label" => "Fond de Verre",
                      "value" => (int) $proposal->DTLBottomGrade()->value() ?? 0,
                  ],
              ],
          ];

          $proposals[] = $DTLProposal;
      }
  }

  return $proposals;
}

function refreshProjectStepsCache($project, $steps) {
    $apiCache = kirby()->cache('api');
    $apiCache->set($project->slug() . '_' . 'steps', $steps);
}