<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Controller;
use App\Repositories\SettingRepository;
use App\Services\AuditService;

final class SettingsController extends Controller {
    public function branding(): void {
        require_role(['admin']);
        $settings = (new SettingRepository())->allAssoc();
        $this->view('settings/branding', compact('settings'));
    }

    public function saveBranding(): void {
        require_role(['admin']);
        verify_csrf();
        $repo = new SettingRepository();

        $logoPath = trim((string)($repo->get('logo_path', 'assets/img/default-logo.png')));
        if (!empty($_FILES['logo_file']['tmp_name']) && is_uploaded_file($_FILES['logo_file']['tmp_name'])) {
            $ext = strtolower(pathinfo((string)$_FILES['logo_file']['name'], PATHINFO_EXTENSION)) ?: 'png';
            $allowed = ['png','jpg','jpeg','webp','svg'];
            if (in_array($ext, $allowed, true)) {
                $dir = dirname(__DIR__, 2) . '/storage/uploads/branding';
                if (!is_dir($dir)) @mkdir($dir, 0777, true);
                $name = 'logo_' . time() . '.' . $ext;
                $target = $dir . '/' . $name;
                if (@move_uploaded_file($_FILES['logo_file']['tmp_name'], $target)) {
                    $logoPath = 'storage/uploads/branding/' . $name;
                }
            }
        }

        $repo->saveBulk([
            'system_name_ar' => trim((string)($_POST['system_name_ar'] ?? 'نظام فخر لإدارة التأجير والبيع والطابور')),
            'system_name_en' => trim((string)($_POST['system_name_en'] ?? 'Fakhr Rental & Queue Management System')),
            'shop_name_ar' => trim((string)($_POST['shop_name_ar'] ?? 'فخر الأصالة العمانية')),
            'shop_name_en' => trim((string)($_POST['shop_name_en'] ?? 'Fakhr Oman')),
            'site_url' => trim((string)($_POST['site_url'] ?? '')),
            'logo_path' => $logoPath,
            'queue_screen_message' => trim((string)($_POST['queue_screen_message'] ?? 'أهلاً بكم')),
        ]);
        (new AuditService())->log('settings', 'branding_update');
        flash('success', 'تم حفظ الهوية العامة للنظام');
        redirect(base_url('?page=settings_branding'));
    }

    public function whatsapp(): void {
        require_role(['admin']);
        $settings = (new SettingRepository())->allAssoc();
        $this->view('settings/whatsapp', compact('settings'));
    }

    public function saveWhatsapp(): void {
        require_role(['admin']);
        verify_csrf();
        $repo = new SettingRepository();
        $repo->saveBulk([
            'ultra_instance_id' => trim((string)($_POST['ultra_instance_id'] ?? '')),
            'ultra_token' => trim((string)($_POST['ultra_token'] ?? '')),
            'queue_notify_before' => (string)max(1, (int)($_POST['queue_notify_before'] ?? 3)),
            'queue_message_template' => trim((string)($_POST['queue_message_template'] ?? '')),
            'queue_now_template' => trim((string)($_POST['queue_now_template'] ?? '')),
            'queue_public_title' => trim((string)($_POST['queue_public_title'] ?? 'متابعة الدور')),
            'queue_poll_ms' => (string)max(1000, (int)($_POST['queue_poll_ms'] ?? 2000)),
            'queue_sound_enabled' => !empty($_POST['queue_sound_enabled']) ? '1' : '0',
            'queue_ticket_price' => number_format(max(0, (float)($_POST['queue_ticket_price'] ?? 0)), 3, '.', ''),
            'queue_currency' => trim((string)($_POST['queue_currency'] ?? 'ر.ع')),
            'queue_prefix_default' => strtoupper(substr(trim((string)($_POST['queue_prefix_default'] ?? 'A')) ?: 'A', 0, 3)),
            'tailoring_unit_price' => number_format(max(0, (float)($_POST['tailoring_unit_price'] ?? 0)), 3, '.', ''),
            'tailoring_ready_template' => trim((string)($_POST['tailoring_ready_template'] ?? 'مرحباً {name}، تم تجهيز المصر الخاصة بك. رقم التذكرة: {ticket_no}. يمكنك الحضور للاستلام.')),
            'studio_booking_price' => number_format(max(0, (float)($_POST['studio_booking_price'] ?? 0)), 3, '.', ''),
            'studio_booking_create_template' => trim((string)($_POST['studio_booking_create_template'] ?? 'مرحباً {name}، تم تأكيد حجز استوديو التصوير بتاريخ {booking_date} من {start_time} إلى {end_time}. السعر: {price} {currency}.')),
            'studio_booking_update_template' => trim((string)($_POST['studio_booking_update_template'] ?? 'مرحباً {name}، تم تحديث حجز استوديو التصوير بتاريخ {booking_date} من {start_time} إلى {end_time}. السعر: {price} {currency}.')),
        ]);
        (new AuditService())->log('settings', 'whatsapp_update');
        flash('success', 'تم حفظ إعدادات واتساب والطابور');
        redirect(base_url('?page=settings_whatsapp'));
    }
}
