<?php

namespace App\Controllers;

use App\Libraries\LeadMailer;
use App\Models\AdminUserModel;
use App\Models\LeadModel;
use App\Models\SettingModel;
use Config\Services;

class Admin extends BaseController
{
    private const STATUSES = ["new", "contacted", "qualified", "closed"];

    public function index()
    {
        $users = new AdminUserModel();
        if ($users->countAllResults() === 0) {
            return redirect()->to(base_url("admin/setup"));
        }

        return session()->get("admin_id")
            ? redirect()->to(base_url("admin/leads"))
            : redirect()->to(base_url("admin/login"));
    }

    public function setup()
    {
        $users = new AdminUserModel();
        if ($users->countAllResults() > 0) {
            return redirect()->to(base_url("admin/login"));
        }

        if ($this->request->getMethod() === "post") {
            $rules = [
                "name" => "required|min_length[2]|max_length[100]",
                "email" => "required|valid_email|max_length[190]",
                "password" => "required|min_length[12]|max_length[255]",
                "password_confirm" => "required|matches[password]",
            ];

            if ($this->validate($rules)) {
                $id = $users->insert([
                    "name" => trim((string) $this->request->getPost("name")),
                    "email" => strtolower(
                        trim((string) $this->request->getPost("email")),
                    ),
                    "password_hash" => password_hash(
                        (string) $this->request->getPost("password"),
                        PASSWORD_DEFAULT,
                    ),
                ]);
                session()->regenerate(true);
                session()->set([
                    "admin_id" => $id,
                    "admin_name" => $this->request->getPost("name"),
                    "admin_email" => $this->request->getPost("email"),
                ]);
                return redirect()
                    ->to(base_url("admin/leads"))
                    ->with("success", "Your admin account is ready.");
            }
        }

        return view("admin/auth", [
            "mode" => "setup",
            "errors" => $this->validator ? $this->validator->getErrors() : [],
        ]);
    }

    public function login()
    {
        $users = new AdminUserModel();
        if ($users->countAllResults() === 0) {
            return redirect()->to(base_url("admin/setup"));
        }
        if (session()->get("admin_id")) {
            return redirect()->to(base_url("admin/leads"));
        }

        if ($this->request->getMethod() === "post") {
            $key =
                "admin-login-" . hash("sha256", $this->request->getIPAddress());
            if (!Services::throttler()->check($key, 5, 300)) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        "Too many attempts. Try again in five minutes.",
                    );
            }

            $email = strtolower(
                trim((string) $this->request->getPost("email")),
            );
            $user = $users->where("email", $email)->first();
            if (
                $user &&
                password_verify(
                    (string) $this->request->getPost("password"),
                    $user["password_hash"],
                )
            ) {
                session()->regenerate(true);
                session()->set([
                    "admin_id" => $user["id"],
                    "admin_name" => $user["name"],
                    "admin_email" => $user["email"],
                ]);
                $users->update($user["id"], [
                    "last_login_at" => date("Y-m-d H:i:s"),
                ]);
                return redirect()->to(base_url("admin/leads"));
            }

            return redirect()
                ->back()
                ->withInput()
                ->with("error", "Incorrect email or password.");
        }

        return view("admin/auth", ["mode" => "login", "errors" => []]);
    }

    public function logout()
    {
        session()->remove(["admin_id", "admin_name", "admin_email"]);
        session()->regenerate(true);
        return redirect()
            ->to(base_url("admin/login"))
            ->with("success", "You have been signed out.");
    }

    public function leads()
    {
        $model = new LeadModel();
        $status = (string) $this->request->getGet("status");
        $search = trim((string) $this->request->getGet("search"));

        if (in_array($status, self::STATUSES, true)) {
            $model->where("status", $status);
        }
        if ($search !== "") {
            $model
                ->groupStart()
                ->like("name", $search)
                ->orLike("email", $search)
                ->orLike("business_name", $search)
                ->orLike("industry", $search)
                ->groupEnd();
        }

        $leads = $model->orderBy("created_at", "DESC")->findAll(100);
        $metricsModel = new LeadModel();

        return view("admin/leads", [
            "leads" => $leads,
            "statuses" => self::STATUSES,
            "activeStatus" => $status,
            "search" => $search,
            "metrics" => [
                "total" => $metricsModel->countAll(),
                "new" => (new LeadModel())
                    ->where("status", "new")
                    ->countAllResults(),
                "qualified" => (new LeadModel())
                    ->where("status", "qualified")
                    ->countAllResults(),
                "closed" => (new LeadModel())
                    ->where("status", "closed")
                    ->countAllResults(),
            ],
        ]);
    }

    public function updateLeadStatus($id)
    {
        $status = (string) $this->request->getPost("status");
        if (!in_array($status, self::STATUSES, true)) {
            return redirect()->back()->with("error", "Invalid lead status.");
        }

        (new LeadModel())->update((int) $id, ["status" => $status]);
        return redirect()->back()->with("success", "Lead status updated.");
    }

    public function settings()
    {
        $model = new SettingModel();
        $kitAssetBase =
            basename(rtrim(FCPATH, "\\/")) === "public"
                ? "assets/"
                : "public/assets/";
        $defaults = [
            "call_phone_display" => "+91 98765 43210",
            "call_phone_href" => "+919876543210",
            "whatsapp_number" => "919876543210",
            "social_instagram" => "",
            "social_behance" => "",
            "social_facebook" => "",
            "social_linkedin" => "",
            "social_youtube" => "",
            "social_pinterest" => "",
            "whatsapp_delivery_enabled" => "0",
            "whatsapp_cloud_phone_number_id" => "",
            "whatsapp_cloud_graph_version" => "",
            "whatsapp_cloud_template_name" => "logo_launch_kit_delivery",
            "whatsapp_cloud_template_language" => "en",
            "logo_launch_kit_url" => base_url(
                $kitAssetBase . "downloads/brandsquare-logo-launch-kit.pdf",
            ),
            "whatsapp_redesign_delivery_enabled" => "0",
            "whatsapp_redesign_template_name" =>
                "logo_redesign_scorecard_delivery",
            "whatsapp_redesign_template_language" => "en",
            "logo_redesign_scorecard_url" => base_url(
                $kitAssetBase .
                    "downloads/brandsquare-logo-redesign-scorecard.pdf",
            ),
            "smtp_enabled" => "0",
            "smtp_host" => "",
            "smtp_port" => "587",
            "smtp_username" => "",
            "smtp_crypto" => "tls",
            "smtp_from_email" => "",
            "smtp_from_name" => "BrandSquare",
            "notification_email" => "",
        ];

        if ($this->request->getMethod() === "post") {
            $rules = [
                "call_phone_display" => "required|max_length[30]",
                "call_phone_href" => "required|max_length[30]",
                "whatsapp_number" => "required|max_length[30]",
                "smtp_port" =>
                    "required|integer|greater_than[0]|less_than[65536]",
                "smtp_crypto" => "required|in_list[tls,ssl,none]",
                "smtp_from_email" => "permit_empty|valid_email|max_length[190]",
                "notification_email" =>
                    "permit_empty|valid_email|max_length[190]",
                "social_instagram" => "permit_empty|max_length[500]",
                "social_behance" => "permit_empty|max_length[500]",
                "social_facebook" => "permit_empty|max_length[500]",
                "social_linkedin" => "permit_empty|max_length[500]",
                "social_youtube" => "permit_empty|max_length[500]",
                "social_pinterest" => "permit_empty|max_length[500]",
                "whatsapp_cloud_phone_number_id" =>
                    "permit_empty|max_length[100]",
                "whatsapp_cloud_graph_version" =>
                    "permit_empty|max_length[20]|regex_match[/^v[0-9]+\.[0-9]+$/]",
                "whatsapp_cloud_template_name" =>
                    "permit_empty|max_length[100]|regex_match[/^[a-z0-9_]+$/]",
                "whatsapp_cloud_template_language" =>
                    "permit_empty|max_length[15]",
                "logo_launch_kit_url" => "permit_empty|max_length[500]",
                "whatsapp_redesign_template_name" =>
                    "permit_empty|max_length[100]|regex_match[/^[a-z0-9_]+$/]",
                "whatsapp_redesign_template_language" =>
                    "permit_empty|max_length[15]",
                "logo_redesign_scorecard_url" => "permit_empty|max_length[500]",
            ];

            if (!$this->validate($rules)) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        implode(" ", $this->validator->getErrors()),
                    );
            }

            $socialKeys = [
                "social_instagram",
                "social_behance",
                "social_facebook",
                "social_linkedin",
                "social_youtube",
                "social_pinterest",
            ];
            foreach ($socialKeys as $socialKey) {
                $socialUrl = trim((string) $this->request->getPost($socialKey));
                if (
                    $socialUrl !== "" &&
                    (!filter_var($socialUrl, FILTER_VALIDATE_URL) ||
                        !in_array(
                            strtolower(
                                (string) parse_url($socialUrl, PHP_URL_SCHEME),
                            ),
                            ["http", "https"],
                            true,
                        ))
                ) {
                    return redirect()
                        ->back()
                        ->withInput()
                        ->with(
                            "error",
                            "Social profile links must be complete http or https URLs.",
                        );
                }
            }

            $whatsappDeliveryEnabled = $this->request->getPost(
                "whatsapp_delivery_enabled",
            )
                ? "1"
                : "0";
            $kitUrl = trim(
                (string) $this->request->getPost("logo_launch_kit_url"),
            );
            $redesignDeliveryEnabled = $this->request->getPost(
                "whatsapp_redesign_delivery_enabled",
            )
                ? "1"
                : "0";
            $scorecardUrl = trim(
                (string) $this->request->getPost("logo_redesign_scorecard_url"),
            );
            $whatsappToken = trim(
                (string) $this->request->getPost("whatsapp_cloud_access_token"),
            );
            if (
                ($whatsappDeliveryEnabled === "1" ||
                    $redesignDeliveryEnabled === "1") &&
                (!$this->request->getPost("whatsapp_cloud_phone_number_id") ||
                    !$this->request->getPost("whatsapp_cloud_graph_version") ||
                    ($whatsappToken === "" &&
                        $model->value("whatsapp_cloud_access_token", "") ===
                            ""))
            ) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        "Add the shared WhatsApp Phone Number ID, Graph API version, and access token before enabling automated delivery.",
                    );
            }
            if (
                $whatsappDeliveryEnabled === "1" &&
                (!$this->request->getPost("whatsapp_cloud_template_name") ||
                    !$this->request->getPost(
                        "whatsapp_cloud_template_language",
                    ) ||
                    $kitUrl === "")
            ) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        "Complete the Logo Launch Kit template, language, and PDF URL before enabling its delivery.",
                    );
            }
            if (
                $redesignDeliveryEnabled === "1" &&
                (!$this->request->getPost("whatsapp_redesign_template_name") ||
                    !$this->request->getPost(
                        "whatsapp_redesign_template_language",
                    ) ||
                    $scorecardUrl === "")
            ) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        "Complete the Logo Redesign Scorecard template, language, and PDF URL before enabling its delivery.",
                    );
            }
            $documentUrls = [
                [
                    "url" => $kitUrl,
                    "label" => "Logo Launch Kit",
                    "enabled" => $whatsappDeliveryEnabled,
                ],
                [
                    "url" => $scorecardUrl,
                    "label" => "Logo Redesign Scorecard",
                    "enabled" => $redesignDeliveryEnabled,
                ],
            ];
            foreach ($documentUrls as $documentUrl) {
                if (
                    $documentUrl["url"] !== "" &&
                    (!filter_var($documentUrl["url"], FILTER_VALIDATE_URL) ||
                        !in_array(
                            strtolower(
                                (string) parse_url(
                                    $documentUrl["url"],
                                    PHP_URL_SCHEME,
                                ),
                            ),
                            ["http", "https"],
                            true,
                        ))
                ) {
                    return redirect()
                        ->back()
                        ->withInput()
                        ->with(
                            "error",
                            "The " .
                                $documentUrl["label"] .
                                " URL must be a complete http or https URL.",
                        );
                }
                if (
                    $documentUrl["enabled"] === "1" &&
                    strtolower(
                        (string) parse_url($documentUrl["url"], PHP_URL_SCHEME),
                    ) !== "https"
                ) {
                    return redirect()
                        ->back()
                        ->withInput()
                        ->with(
                            "error",
                            "Automated " .
                                $documentUrl["label"] .
                                " delivery requires a public HTTPS PDF URL.",
                        );
                }
            }

            $enabled = $this->request->getPost("smtp_enabled") ? "1" : "0";
            if (
                $enabled === "1" &&
                (!$this->request->getPost("smtp_host") ||
                    !$this->request->getPost("notification_email"))
            ) {
                return redirect()
                    ->back()
                    ->withInput()
                    ->with(
                        "error",
                        "SMTP host and notification email are required when email notifications are enabled.",
                    );
            }

            $values = [
                "call_phone_display" => trim(
                    (string) $this->request->getPost("call_phone_display"),
                ),
                "call_phone_href" => preg_replace(
                    "/[^0-9+]/",
                    "",
                    (string) $this->request->getPost("call_phone_href"),
                ),
                "whatsapp_number" => preg_replace(
                    "/\D/",
                    "",
                    (string) $this->request->getPost("whatsapp_number"),
                ),
                "social_instagram" => trim(
                    (string) $this->request->getPost("social_instagram"),
                ),
                "social_behance" => trim(
                    (string) $this->request->getPost("social_behance"),
                ),
                "social_facebook" => trim(
                    (string) $this->request->getPost("social_facebook"),
                ),
                "social_linkedin" => trim(
                    (string) $this->request->getPost("social_linkedin"),
                ),
                "social_youtube" => trim(
                    (string) $this->request->getPost("social_youtube"),
                ),
                "social_pinterest" => trim(
                    (string) $this->request->getPost("social_pinterest"),
                ),
                "whatsapp_delivery_enabled" => $whatsappDeliveryEnabled,
                "whatsapp_cloud_phone_number_id" => trim(
                    (string) $this->request->getPost(
                        "whatsapp_cloud_phone_number_id",
                    ),
                ),
                "whatsapp_cloud_graph_version" => trim(
                    (string) $this->request->getPost(
                        "whatsapp_cloud_graph_version",
                    ),
                ),
                "whatsapp_cloud_template_name" => trim(
                    (string) $this->request->getPost(
                        "whatsapp_cloud_template_name",
                    ),
                ),
                "whatsapp_cloud_template_language" => trim(
                    (string) $this->request->getPost(
                        "whatsapp_cloud_template_language",
                    ),
                ),
                "logo_launch_kit_url" => $kitUrl,
                "whatsapp_redesign_delivery_enabled" => $redesignDeliveryEnabled,
                "whatsapp_redesign_template_name" => trim(
                    (string) $this->request->getPost(
                        "whatsapp_redesign_template_name",
                    ),
                ),
                "whatsapp_redesign_template_language" => trim(
                    (string) $this->request->getPost(
                        "whatsapp_redesign_template_language",
                    ),
                ),
                "logo_redesign_scorecard_url" => $scorecardUrl,
                "smtp_enabled" => $enabled,
                "smtp_host" => trim(
                    (string) $this->request->getPost("smtp_host"),
                ),
                "smtp_port" => (string) $this->request->getPost("smtp_port"),
                "smtp_username" => trim(
                    (string) $this->request->getPost("smtp_username"),
                ),
                "smtp_crypto" => (string) $this->request->getPost(
                    "smtp_crypto",
                ),
                "smtp_from_email" => strtolower(
                    trim((string) $this->request->getPost("smtp_from_email")),
                ),
                "smtp_from_name" => trim(
                    (string) $this->request->getPost("smtp_from_name"),
                ),
                "notification_email" => strtolower(
                    trim(
                        (string) $this->request->getPost("notification_email"),
                    ),
                ),
            ];

            foreach ($values as $key => $value) {
                $model->setValue($key, $value);
            }

            $password = (string) $this->request->getPost("smtp_password");
            if ($password !== "") {
                $encrypted = base64_encode(
                    Services::encrypter()->encrypt($password),
                );
                $model->setValue("smtp_password", $encrypted, true);
            }
            if ($whatsappToken !== "") {
                $encrypted = base64_encode(
                    Services::encrypter()->encrypt($whatsappToken),
                );
                $model->setValue(
                    "whatsapp_cloud_access_token",
                    $encrypted,
                    true,
                );
            }

            if ($this->request->getPost("action") === "test") {
                $testSettings = $model->values($defaults);
                $sent = (new LeadMailer())->sendTest($testSettings);
                return redirect()
                    ->back()
                    ->with(
                        $sent ? "success" : "error",
                        $sent
                            ? "Test email sent successfully."
                            : "The test email could not be sent. Check the SMTP details and server logs.",
                    );
            }

            return redirect()->back()->with("success", "Settings saved.");
        }

        $settings = $model->values($defaults);
        return view("admin/settings", [
            "settings" => $settings,
            "passwordConfigured" => $model->value("smtp_password", "") !== "",
            "whatsappTokenConfigured" =>
                $model->value("whatsapp_cloud_access_token", "") !== "",
        ]);
    }
}
