<?php
declare(strict_types=1);

namespace App\Modules\Settings\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Settings\Models\SystemConfig;
use App\Modules\Settings\Services\BrandingService;

class BrandingController extends Controller
{
    public function index(Request $request): Response
    {
        return $this->view('Settings.Views.branding', [
            'logo'          => BrandingService::logo(),
            'clubNameAr'    => BrandingService::clubNameAr(),
            'clubNameEn'    => BrandingService::clubNameEn(),
            'subtitle'      => BrandingService::subtitle(),
            'carnetDesign'  => BrandingService::carnetDesign(),
            'receiptDesign' => BrandingService::receiptDesign(),
        ]);
    }

    public function updateLogo(Request $request): Response
    {
        // Handle club name / subtitle fields
        $clubNameAr = trim($request->post('club_name_ar', ''));
        $clubNameEn = trim($request->post('club_name_en', ''));
        $subtitle   = trim($request->post('club_subtitle', ''));

        if ($clubNameAr !== '') {
            SystemConfig::set('branding.club_name_ar', $clubNameAr);
        }
        if ($clubNameEn !== '') {
            SystemConfig::set('branding.club_name_en', $clubNameEn);
        }
        SystemConfig::set('branding.club_subtitle', $subtitle);

        // Handle logo upload — stored as base64 data URI in DB (survives Docker rebuilds)
        if ($request->hasFile('logo_file')) {
            $file = $request->file('logo_file');
            if ($file && $file['error'] === UPLOAD_ERR_OK) {
                // Validate size (max 2MB)
                if ($file['size'] > 2 * 1024 * 1024) {
                    return $this->redirect('/settings/branding')->withError('حجم الشعار يجب أن لا يتجاوز 2 ميجا');
                }

                // Validate MIME type
                $finfo = new \finfo(FILEINFO_MIME_TYPE);
                $mimeType = $finfo->file($file['tmp_name']);
                $allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/svg+xml', 'image/webp'];
                if (!in_array($mimeType, $allowedTypes)) {
                    return $this->redirect('/settings/branding')->withError('نوع الملف غير مسموح (PNG, JPG, SVG, WebP فقط)');
                }

                // Read file and encode as base64 data URI
                $fileData = file_get_contents($file['tmp_name']);
                if ($fileData === false) {
                    return $this->redirect('/settings/branding')->withError('فشل في قراءة الملف');
                }

                $dataUri = 'data:' . $mimeType . ';base64,' . base64_encode($fileData);
                SystemConfig::set('branding.logo_data', $dataUri);
                SystemConfig::set('branding.logo_path', '');
                BrandingService::clearCache();
            }
        }

        // Handle logo removal
        if ($request->post('remove_logo') === '1') {
            SystemConfig::set('branding.logo_data', '');
            SystemConfig::set('branding.logo_path', '');
        }

        BrandingService::clearCache();
        return $this->redirect('/settings/branding')->withSuccess('تم تحديث الهوية البصرية بنجاح');
    }

    public function updateCarnetDesign(Request $request): Response
    {
        $design = [
            'front_bg_color'         => $request->post('front_bg_color', '#0D7377'),
            'front_text_color'       => $request->post('front_text_color', '#ffffff'),
            'front_show_subtitle'    => $request->post('front_show_subtitle') === '1',
            'front_show_english_name'=> $request->post('front_show_english_name') === '1',
            'front_show_member_type' => $request->post('front_show_member_type') === '1',
            'front_show_qr'          => $request->post('front_show_qr') === '1',
            'front_qr_position'      => $request->post('front_qr_position', 'bottom-left'),
            'front_logo_position'    => $request->post('front_logo_position', 'top-center'),
            'back_show_branch_strip' => $request->post('back_show_branch_strip') === '1',
            'back_strip_color'       => $request->post('back_strip_color', '#0D7377'),
            'back_show_instructions' => $request->post('back_show_instructions') === '1',
            'back_instructions_text' => trim($request->post('back_instructions_text', '')),
            'back_fields'            => $request->post('back_fields') ? (array) $request->post('back_fields') : ['full_name_ar', 'membership_number'],
        ];

        $json = json_encode($design, JSON_UNESCAPED_UNICODE);
        SystemConfig::set('branding.carnet_design', $json);
        BrandingService::clearCache();

        return $this->redirect('/settings/branding')->withSuccess('تم تحديث تصميم الكارنيه بنجاح');
    }

    public function updateReceiptDesign(Request $request): Response
    {
        $design = [
            'show_logo'              => $request->post('show_logo') === '1',
            'show_watermark'         => $request->post('show_watermark') === '1',
            'watermark_text'         => trim($request->post('watermark_text', '')),
            'watermark_opacity'      => max(0.01, min(0.2, (float) $request->post('watermark_opacity', '0.06'))),
            'header_color'           => $request->post('header_color', '#0D7377'),
            'show_footer_print_info' => $request->post('show_footer_print_info') === '1',
        ];

        $json = json_encode($design, JSON_UNESCAPED_UNICODE);
        SystemConfig::set('branding.receipt_design', $json);
        BrandingService::clearCache();

        return $this->redirect('/settings/branding')->withSuccess('تم تحديث تصميم الإيصال بنجاح');
    }
}
