<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CompanyModel;

/**
 * إعدادات الموقع الإلكتروني العام الخاص بالشركة النشطة:
 * تفعيل/تعطيل، رابط الموقع (slug)، الألوان والخط، نصوص (نبذة/رؤية/رسالة)،
 * روابط التواصل الاجتماعي، ونص الفوتر.
 */
class SiteSettingsController extends BaseController
{
    public function edit()
    {
        $companyId = $this->currentCompanyId();
        $company = $companyId ? (new CompanyModel())->find($companyId) : null;

        return view('admin/site_settings/form', ['company' => $company]);
    }

    public function update()
    {
        $companyId = $this->currentCompanyId();
        if (! $companyId) {
            return redirect()->to('/admin/site-settings')->with('error', 'اختر شركة نشطة أولاً.');
        }

        $model = new CompanyModel();
        $company = $model->find($companyId);

        $slugInput = trim((string) $this->request->getPost('slug'));
        $slug = $slugInput !== '' ? url_title(strtolower($slugInput), '-', true) : ($company['slug'] ?? null);
        if (! $slug) {
            $slug = $model->generateSlug($company['name'], $companyId);
        } else {
            // تأكد إن الـ slug مش مستخدم بشركة تانية
            $existing = $model->where('slug', $slug)->where('id !=', $companyId)->first();
            if ($existing) {
                $slug = $model->generateSlug($slug, $companyId);
            }
        }

        $data = [
            'slug' => $slug,
            'is_site_enabled' => $this->request->getPost('is_site_enabled') ? 1 : 0,
            'site_primary_color' => $this->request->getPost('site_primary_color') ?: '#1e1e2d',
            'site_font' => $this->request->getPost('site_font') ?: 'Tajawal',
            'site_tagline' => $this->request->getPost('site_tagline'),
            'site_about_text' => $this->request->getPost('site_about_text'),
            'site_vision' => $this->request->getPost('site_vision'),
            'site_mission' => $this->request->getPost('site_mission'),
            'site_services_text' => $this->request->getPost('site_services_text'),
            'site_footer_text' => $this->request->getPost('site_footer_text'),
            'site_facebook_url' => $this->request->getPost('site_facebook_url'),
            'site_twitter_url' => $this->request->getPost('site_twitter_url'),
            'site_instagram_url' => $this->request->getPost('site_instagram_url'),
            'site_whatsapp_number' => $this->request->getPost('site_whatsapp_number'),
        ];

        // رفع شعار جديد لو اتحدد (نفس منطق شاشة الإعدادات العامة)
        $logoFile = $this->request->getFile('logo');
        if ($logoFile && $logoFile->isValid() && ! $logoFile->hasMoved()) {
            if (! is_dir(FCPATH . 'uploads/logos')) {
                mkdir(FCPATH . 'uploads/logos', 0755, true);
            }
            $newName = 'company_' . $companyId . '_' . time() . '.' . $logoFile->getExtension();
            $logoFile->move(FCPATH . 'uploads/logos', $newName);
            $data['logo'] = $newName;
        }

        $model->update($companyId, $data);

        $this->logActivity('update_site_settings', 'عدّل إعدادات الموقع الإلكتروني العام');

        return redirect()->to('/admin/site-settings')->with('message', lang('App.saved_successfully'));
    }
}
