<?php

namespace App\Controllers\Site;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\ContactMessageModel;
use App\Models\ProductModel;
use App\Models\SiteSlideModel;
use App\Models\TestimonialModel;

/**
 * الموقع الإلكتروني العام لكل شركة - بدون تسجيل دخول، متاح لأي زائر.
 * كل الشاشات بتاخد "slug" الشركة من الرابط، وتفشل بـ 404 لو الشركة مش موجودة
 * أو الموقع مش مفعّل ليها.
 */
class SiteController extends BaseController
{
    private function loadCompanyOrFail(string $slug): ?array
    {
        return (new CompanyModel())->findBySlug($slug);
    }

    public function home(string $slug)
    {
        $company = $this->loadCompanyOrFail($slug);
        if (! $company) return $this->pageNotFound();

        $slides = (new SiteSlideModel())->forCompany($company['id'])->where('is_active', 1)->orderBy('sort_order', 'ASC')->findAll();
        $products = (new ProductModel())->forCompany($company['id'])->where('is_active', 1)->findAll(6);
        $testimonials = (new TestimonialModel())->forCompany($company['id'])->where('is_active', 1)->findAll();

        return view('site/home', compact('company', 'slides', 'products', 'testimonials'));
    }

    public function about(string $slug)
    {
        $company = $this->loadCompanyOrFail($slug);
        if (! $company) return $this->pageNotFound();

        return view('site/about', compact('company'));
    }

    public function products(string $slug)
    {
        $company = $this->loadCompanyOrFail($slug);
        if (! $company) return $this->pageNotFound();

        $products = (new ProductModel())->forCompany($company['id'])->where('is_active', 1)->findAll();

        return view('site/products', compact('company', 'products'));
    }

    public function contact(string $slug)
    {
        $company = $this->loadCompanyOrFail($slug);
        if (! $company) return $this->pageNotFound();

        return view('site/contact', ['company' => $company, 'recaptchaSiteKey' => getenv('RECAPTCHA_SITE_KEY')]);
    }

    public function submitContact(string $slug)
    {
        $company = $this->loadCompanyOrFail($slug);
        if (! $company) return $this->pageNotFound();

        // تحقق reCAPTCHA
        $recaptchaResponse = $this->request->getPost('g-recaptcha-response');
        if (! $this->verifyRecaptcha($recaptchaResponse)) {
            return redirect()->back()->withInput()->with('error', 'يرجى تأكيد أنك لست روبوت (reCAPTCHA).');
        }

        $rules = [
            'name' => 'required|min_length[2]',
            'email' => 'required|valid_email',
            'message' => 'required|min_length[5]',
        ];

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

        (new ContactMessageModel())->insert([
            'company_id' => $company['id'],
            'name' => $this->request->getPost('name'),
            'email' => $this->request->getPost('email'),
            'phone' => $this->request->getPost('phone'),
            'subject' => $this->request->getPost('subject'),
            'message' => $this->request->getPost('message'),
            'is_read' => 0,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        // إشعار بريدي فوري للشركة (اختياري - لو عندها بريد مسجل)
        if (! empty($company['email'])) {
            $email = \Config\Services::email();
            $email->setTo($company['email']);
            $email->setSubject('رسالة جديدة من موقعكم الإلكتروني');
            $email->setMessage(
                "اسم المرسل: " . $this->request->getPost('name') . "\n" .
                "البريد: " . $this->request->getPost('email') . "\n" .
                "الهاتف: " . $this->request->getPost('phone') . "\n\n" .
                "الرسالة:\n" . $this->request->getPost('message')
            );
            $email->send();
        }

        return redirect()->to('/site/' . $slug . '/contact')->with('message', 'تم إرسال رسالتك بنجاح، هيتم التواصل معك قريباً.');
    }

    private function verifyRecaptcha(?string $response): bool
    {
        $secret = getenv('RECAPTCHA_SECRET_KEY');

        // لو مفيش مفاتيح reCAPTCHA متظبطة في .env، نتجاوز الفحص عشان النظام يفضل شغال أثناء التطوير
        if (! $secret) return true;

        if (! $response) return false;

        $curl = curl_init('https://www.google.com/recaptcha/api/siteverify');
        curl_setopt_array($curl, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query(['secret' => $secret, 'response' => $response]),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
        ]);
        $result = curl_exec($curl);
        curl_close($curl);

        $json = json_decode((string) $result, true);
        return (bool) ($json['success'] ?? false);
    }

    private function pageNotFound()
    {
        return $this->response->setStatusCode(404)->setBody(view('site/not_found'));
    }
}
