<?php

namespace App\Controllers;

use App\Models\IndustryModel;

class Industries extends BaseController
{
    public function index()
    {
        $search = trim((string) $this->request->getGet("search"));
        $model = new IndustryModel();
        if ($search !== "") {
            $model
                ->groupStart()
                ->like("name", $search)
                ->orLike("slug", $search)
                ->orLike("meta_title", $search)
                ->groupEnd();
        }

        return view("admin/industries/index", [
            "industries" => $model
                ->orderBy("sort_order", "ASC")
                ->orderBy("name", "ASC")
                ->findAll(250),
            "search" => $search,
            "metrics" => [
                "total" => (new IndustryModel())->countAll(),
                "active" => (new IndustryModel())
                    ->where("is_active", 1)
                    ->countAllResults(),
                "inactive" => (new IndustryModel())
                    ->where("is_active", 0)
                    ->countAllResults(),
            ],
        ]);
    }

    public function create()
    {
        if ($this->request->getMethod() === "post") {
            return $this->saveIndustry();
        }

        return view("admin/industries/form", [
            "industry" => null,
            "mode" => "create",
        ]);
    }

    public function show($id)
    {
        $industry = (new IndustryModel())->find((int) $id);
        if (!$industry) {
            return $this->notFound();
        }

        return view("admin/industries/show", ["industry" => $industry]);
    }

    public function edit($id)
    {
        $industry = (new IndustryModel())->find((int) $id);
        if (!$industry) {
            return $this->notFound();
        }
        if ($this->request->getMethod() === "post") {
            return $this->saveIndustry((int) $id);
        }

        return view("admin/industries/form", [
            "industry" => $industry,
            "mode" => "edit",
        ]);
    }

    private function saveIndustry(?int $id = null)
    {
        $rules = [
            "name" => "required|min_length[2]|max_length[120]",
            "slug" =>
                "required|min_length[2]|max_length[140]|regex_match[/^[a-z0-9]+(?:-[a-z0-9]+)*$/]",
            "meta_title" => "required|min_length[10]|max_length[180]",
            "meta_description" => "required|min_length[30]|max_length[320]",
            "hero_heading" => "required|min_length[10]|max_length[220]",
            "hero_text" => "required|min_length[30]|max_length[1200]",
            "challenge_heading" => "required|min_length[10]|max_length[220]",
            "challenge_text" => "required|min_length[30]|max_length[1600]",
            "primary_color" => "required|regex_match[/^#[0-9a-fA-F]{6}$/]",
            "accent_color" => "required|regex_match[/^#[0-9a-fA-F]{6}$/]",
            "sort_order" => "required|integer|greater_than_equal_to[0]",
        ];
        if (!$this->validate($rules)) {
            return redirect()
                ->back()
                ->withInput()
                ->with("error", implode(" ", $this->validator->getErrors()));
        }

        $slug = strtolower(trim((string) $this->request->getPost("slug")));
        $duplicate = (new IndustryModel())->where("slug", $slug);
        if ($id !== null) {
            $duplicate->where("id !=", $id);
        }
        if ($duplicate->first()) {
            return redirect()
                ->back()
                ->withInput()
                ->with("error", "That page URL is already in use.");
        }

        $data = [
            "name" => trim((string) $this->request->getPost("name")),
            "slug" => $slug,
            "meta_title" => trim(
                (string) $this->request->getPost("meta_title"),
            ),
            "meta_description" => trim(
                (string) $this->request->getPost("meta_description"),
            ),
            "hero_heading" => trim(
                (string) $this->request->getPost("hero_heading"),
            ),
            "hero_text" => trim((string) $this->request->getPost("hero_text")),
            "challenge_heading" => trim(
                (string) $this->request->getPost("challenge_heading"),
            ),
            "challenge_text" => trim(
                (string) $this->request->getPost("challenge_text"),
            ),
            "primary_color" => strtolower(
                (string) $this->request->getPost("primary_color"),
            ),
            "accent_color" => strtolower(
                (string) $this->request->getPost("accent_color"),
            ),
            "is_active" => $this->request->getPost("is_active") ? 1 : 0,
            "sort_order" => (int) $this->request->getPost("sort_order"),
        ];

        $industries = new IndustryModel();
        if ($id === null) {
            $id = (int) $industries->insert($data);
        } else {
            $industries->update($id, $data);
        }

        return redirect()
            ->to(base_url("admin/industries/" . $id))
            ->with(
                "success",
                $this->request->getPost("is_active")
                    ? "Industry page saved and published."
                    : "Industry page saved as inactive.",
            );
    }

    private function notFound()
    {
        return redirect()
            ->to(base_url("admin/industries"))
            ->with("error", "Industry not found.");
    }
}
