<?php

namespace App\Console\Commands;

use App\Models\Article;

class ImportImageArticleCommand extends BaseImportCommand
{
    protected $signature = 'import:image_article';
    private $path = "csv/article_image.csv";
    const COMPANY_ID = 2;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $path = storage_path($this->path);

        $spreadsheet = $this->loadSpreadsheet($path);

        $worksheet = $spreadsheet->getActiveSheet();

        $maxRow = $worksheet->getHighestRow('A');

        for ($i = 2; $i < $maxRow; $i++) {
            $articleBuildingId = $worksheet->getCell("A{$i}")->getValue();
            $article = Article::where("building_id", $articleBuildingId)->first();

            $this->saveRelationImageArticle($article, $worksheet, $i);
            $this->info("# {$i}/{$maxRow} " . date("Y-m-d H:i:s") . " article: {$articleBuildingId}");
        }
    }

    private function saveRelationImageArticle($article, $worksheet, $index)
    {
        $floorImagePath = $worksheet->getCell("C{$index}")->getValue();

        $floorImageName = $this->getImageNameFromPath($floorImagePath);
        $listCurrentImagePath = $this->getListCurrentImage($article, $worksheet, $index);

        if (empty($article)) {
            $this->error("Empty article {$article->building_id}");
            return;
        }

        $floorImageName = str_replace(".jpg", ".JPG", $floorImageName);

        $currentFloorPath = "public/sai/{$floorImageName}";

        $article->update(["floor_file_path" => $currentFloorPath]);
        $article->listImages()->delete();
        $article->listImages()->createMany($listCurrentImagePath);
    }

    private function getImageNameFromPath($path)
    {
        $imageExplode = explode("\\", $path);

        return array_last($imageExplode);
    }

    private function getListCurrentImage($article, $worksheet, $index)
    {
        $startColumnName = "D";
        $endColumnName = "AF";

        $startColumnIndex = \PHPExcel_Cell::columnIndexFromString($startColumnName);
        $endColumnIndex = \PHPExcel_Cell::columnIndexFromString($endColumnName);

        $listImages = [];
        $listCurrentImages = [];

        for ($columnIndex = ($startColumnIndex - 1); $columnIndex <= $endColumnIndex; $columnIndex++) {
            $columnName = \PHPExcel_Cell::stringFromColumnIndex($columnIndex);
            $imagePath = $worksheet->getCell("{$columnName}{$index}")->getValue();

            if (empty($imagePath)) continue;

            $listImages[] = $this->getImageNameFromPath($imagePath);
        }

        $propertySub = $this->getPropertySubImage($article->property);

        foreach ($listImages as $key => $imageName) {
            $imageName = str_replace(".jpg", ".JPG", $imageName);
            $currentFloorPath = "public/sai/{$imageName}";
            $listCurrentImages[] = [
                "file_path" => $currentFloorPath,
                "file_type" => $this->getImageTypeFromName($imageName),
                "file_disp" => 1,
                "property_sub" => $propertySub,
                "order" => $key + 1,
                "company_id" => self::COMPANY_ID
            ];
        }

        return $listCurrentImages;
    }

    private function getPropertySubImage($property)
    {
        if (empty($property)) return 2;

        $isLand = in_array($property, [1, 2, 3]);
        $isHouse = in_array($property, [4, 5]);
        $isMansion = in_array($property, [6, 7]);

        if ($isLand) return 1;
        if ($isHouse) return 1;
        if ($isMansion) return 1;

        return 1;
    }

    private function getImageTypeFromName($name)
    {
        $nameExplode = explode(".", $name);

        return array_last($nameExplode);
    }
}
