<?php

namespace App\Controllers;

use App\Libraries\LeadMailer;
use App\Libraries\WhatsAppKitDelivery;
use App\Models\IndustryModel;
use App\Models\LeadModel;
use Config\Services;

class LeadController extends BaseController
{
    public function store()
    {
        if ($this->request->getPost("website")) {
            return $this->response->setJSON(["success" => true]);
        }

        $isNavigationEnquiry =
            $this->request->getPost("lead_type") === "navigation_enquiry";
        $isIndustryLanding =
            $this->request->getPost("lead_type") === "industry_landing";
        $isGoogleAdsLead =
            $this->request->getPost("lead_type") === "google_ads_lead_magnet";
        $isGoogleAdsRedesignLead =
            $this->request->getPost("lead_type") ===
            "google_ads_redesign_lead_magnet";
        $isWebRedesignScorecard =
            $this->request->getPost("lead_type") ===
            "web_logo_redesign_scorecard";
        $isScorecardLead = $isGoogleAdsRedesignLead || $isWebRedesignScorecard;
        $isTwoFieldLead = $isGoogleAdsLead || $isScorecardLead;

        $key = "lead-" . hash("sha256", $this->request->getIPAddress());
        if (!Services::throttler()->check($key, 5, 3600)) {
            return $this->response->setStatusCode(429)->setJSON([
                "success" => false,
                "message" => "Too many requests. Please try again later.",
            ]);
        }

        $rules = [
            "business_name" =>
                $isNavigationEnquiry || $isTwoFieldLead
                    ? "permit_empty|max_length[150]"
                    : "required|min_length[2]|max_length[150]",
            "industry" =>
                $isNavigationEnquiry || $isTwoFieldLead
                    ? "permit_empty|max_length[120]"
                    : "required|min_length[2]|max_length[120]",
            "message" => "permit_empty|max_length[2000]",
            "style" => "permit_empty|in_list[Minimal,Bold,Elegant,Playful]",
            "budget" => "permit_empty|max_length[50]",
            "name" => "required|min_length[2]|max_length[120]",
            "email" => $isTwoFieldLead
                ? "permit_empty|valid_email|max_length[190]"
                : "required|valid_email|max_length[190]",
            "phone" =>
                $isNavigationEnquiry || $isTwoFieldLead
                    ? "required|min_length[7]|max_length[40]"
                    : "permit_empty|max_length[40]",
            "industry_slug" => "permit_empty|max_length[140]",
        ];

        if (!$this->validate($rules)) {
            return $this->response->setStatusCode(422)->setJSON([
                "success" => false,
                "message" => "Please check the highlighted information.",
                "errors" => $this->validator->getErrors(),
            ]);
        }

        $landingIndustry = null;
        if ($isIndustryLanding) {
            $landingIndustry = (new IndustryModel())
                ->where(
                    "slug",
                    strtolower(
                        trim((string) $this->request->getPost("industry_slug")),
                    ),
                )
                ->where("is_active", 1)
                ->first();
            if (!$landingIndustry) {
                return $this->response->setStatusCode(422)->setJSON([
                    "success" => false,
                    "message" =>
                        "This industry page is no longer available. Please refresh and try again.",
                ]);
            }
        }

        $data = [
            "business_name" =>
                $isNavigationEnquiry || $isTwoFieldLead
                    ? "Not provided"
                    : trim((string) $this->request->getPost("business_name")),
            "industry" => $isNavigationEnquiry
                ? "Logo design enquiry"
                : ($isTwoFieldLead
                    ? ($isScorecardLead
                        ? ($isWebRedesignScorecard
                            ? "Interactive logo redesign scorecard"
                            : "Logo redesign India")
                        : "Logo design India")
                    : ($landingIndustry
                        ? $landingIndustry["name"]
                        : trim((string) $this->request->getPost("industry")))),
            "message" => trim((string) $this->request->getPost("message")),
            "style" => trim((string) $this->request->getPost("style")),
            "budget" => trim((string) $this->request->getPost("budget")),
            "name" => trim((string) $this->request->getPost("name")),
            "email" => strtolower(
                trim((string) $this->request->getPost("email")),
            ),
            "phone" => trim((string) $this->request->getPost("phone")),
            "source" => $isNavigationEnquiry
                ? "navigation enquiry"
                : ($isTwoFieldLead
                    ? ($isScorecardLead
                        ? ($isWebRedesignScorecard
                            ? "web redesign scorecard"
                            : "google ads redesign")
                        : "google ads landing")
                    : ($isIndustryLanding
                        ? substr("industry: " . $landingIndustry["slug"], 0, 50)
                        : "home")),
            "status" => "new",
            "ip_address" => $this->request->getIPAddress(),
            "user_agent" => substr(
                (string) $this->request->getUserAgent(),
                0,
                255,
            ),
        ];

        $model = new LeadModel();
        $model->insert($data);
        $mailer = new LeadMailer();
        $mailer->sendLead($data);
        $mailer->sendCustomerConfirmation($data);
        $kitDelivered = false;
        if ($isGoogleAdsLead) {
            $kitDelivered = (new WhatsAppKitDelivery())->sendLogoLaunchKit(
                $data["phone"],
                $data["name"],
            );
        }
        $scorecardDelivered = false;
        if ($isScorecardLead) {
            $scorecardDelivered = (new WhatsAppKitDelivery())->sendLogoRedesignScorecard(
                $data["phone"],
                $data["name"],
            );
        }

        if ($isGoogleAdsLead) {
            return $this->response->setJSON([
                "success" => true,
                "message" => $kitDelivered
                    ? "Thank you! Your free Logo Launch Kit has been sent on WhatsApp."
                    : "Thank you! Your kit request is saved. Our team will share it on WhatsApp shortly.",
            ]);
        }
        if ($isScorecardLead) {
            return $this->response->setJSON([
                "success" => true,
                "message" => $scorecardDelivered
                    ? "Thank you! Your free Logo Redesign Scorecard has been sent on WhatsApp."
                    : ($isWebRedesignScorecard
                        ? "Your audit result and enquiry are saved. Our team will share the PDF scorecard on WhatsApp shortly."
                        : "Thank you! Your scorecard request is saved. Our team will share it on WhatsApp shortly."),
            ]);
        }

        return $this->response->setJSON([
            "success" => true,
            "message" => $isNavigationEnquiry
                ? "Thanks! Your enquiry has been submitted."
                : ($isTwoFieldLead
                    ? ($isGoogleAdsRedesignLead
                        ? "Thank you! We’ll share your free Logo Redesign Scorecard on WhatsApp shortly."
                        : "Thank you! We’ll share your free Logo Launch Kit on WhatsApp shortly.")
                    : "Thanks! Your brief has been received."),
        ]);
    }
}
