<?php

namespace App\Http\Controllers\Api;

use App\Classes\Common;
use App\Http\Controllers\ApiBaseController;
use Examyou\RestAPI\ApiResponse;
use App\Http\Requests\Api\WebsiteSetting\IndexRequest;
use App\Http\Requests\Api\WebsiteSetting\UpdateRequest;
use App\Models\WebsiteSetting;

class WebsiteSettingController extends ApiBaseController
{
    /**
     * The model associated with the controller.
     *
     * @var string
     */
    protected $model = WebsiteSetting::class;

    /**
     * Get or create the website settings
     *
     * @param IndexRequest $request
     * @return \Examyou\RestAPI\ApiResponse
     */
    public function setting(IndexRequest $request)
    {
        $langId = null;
        $websiteId = null;

        // If website_language_id is provided, convert from xid to id
        if ($request->has('website_language_id') && $request->input('website_language_id')) {
            $langId = Common::getIdFromHash($request->input('website_language_id'));
        }

        // If website_id is provided, convert from xid to id
        if ($request->has('website_id') && $request->input('website_id')) {
            $websiteId = Common::getIdFromHash($request->input('website_id'));
        }

        $settings = WebsiteSetting::getSettings($langId, $websiteId);

        return ApiResponse::make(null, $settings->toArray());
    }

    /**
     * Update the website settings
     *
     * @param UpdateRequest $request
     * @return \Examyou\RestAPI\ApiResponse
     */
    public function updateSetting(UpdateRequest $request)
    {
        $langId = null;
        $websiteId = null;

        // Handle website_language_id (convert xid to id)
        if ($request->has('website_language_id') && $request->input('website_language_id')) {
            $langId = Common::getIdFromHash($request->input('website_language_id'));
        }

        // Handle website_id (convert xid to id)
        if ($request->has('website_id') && $request->input('website_id')) {
            $websiteId = Common::getIdFromHash($request->input('website_id'));
        }

        // Get settings for the specified language and website (creates if not exists)
        $settings = WebsiteSetting::getSettings($langId, $websiteId);

        // Set the website_language_id on the settings
        if ($langId) {
            $settings->website_language_id = $langId;
        }

        // Set the website_id on the settings
        if ($websiteId) {
            $settings->website_id = $websiteId;
        }

        // Update non-file fields
        $fillableFields = [
            // SEO
            'seo_title',
            'seo_description',
            'seo_keywords',
            'seo_author',
            'seo_robots',
            'seo_og_type',
            'seo_og_locale',
            'seo_og_site_name',
            'seo_twitter_card',
            'seo_twitter_site',
            'seo_twitter_creator',

            // Website
            'website_name',
            'website_tagline',
            'website_description',
            'website_phone',
            'website_email',
            'website_address',
            'website_hours',

            // Logo type
            'header_logo_type',

            // Social
            'social_links',
            'show_social_icon',
        ];

        // JSON fields that need to be decoded
        $jsonFields = ['social_links'];

        foreach ($fillableFields as $field) {
            if ($request->has($field)) {
                $value = $request->input($field);

                // Decode JSON strings for JSON fields
                if (in_array($field, $jsonFields) && is_string($value)) {
                    $value = json_decode($value, true);
                }

                $settings->{$field} = $value;
            }
        }

        // Handle file uploads using parent method (uses model's $images property)
        $this->handleFileUploads($settings);

        $settings->save();

        return ApiResponse::make('Website settings updated successfully', $settings->fresh()->toArray());
    }

    /**
     * Get available theme names from resources/views/themes directory
     *
     * @return \Examyou\RestAPI\ApiResponse
     */
    public function getAvailableThemes()
    {
        $themesPath = resource_path('views/themes');
        $themes = [];

        if (is_dir($themesPath)) {
            $directories = scandir($themesPath);
            foreach ($directories as $dir) {
                if ($dir !== '.' && $dir !== '..' && is_dir($themesPath . '/' . $dir)) {
                    $themes[] = [
                        'name' => $dir,
                        'label' => ucfirst(str_replace(['_', '-'], ' ', $dir)),
                    ];
                }
            }
        }

        return ApiResponse::make(null, $themes);
    }

    /**
     * Get available layout components (header/footer) for a specific theme
     *
     * @param string $themeName The theme name (e.g., 'tailwind_theme')
     * @param string $type The component type ('header' or 'footer')
     * @return \Examyou\RestAPI\ApiResponse
     */
    public function getLayoutComponents($themeName, $type)
    {
        // Validate type
        if (!in_array($type, ['header', 'footer'])) {
            return ApiResponse::make('Invalid component type', [], false, 400);
        }

        $componentsPath = resource_path("views/themes/{$themeName}/components/{$type}");
        $layouts = [];

        if (is_dir($componentsPath)) {
            $files = scandir($componentsPath);
            foreach ($files as $file) {
                // Only process .blade.php files (including those with special chars like ⚡)
                if (preg_match('/^(.+)\.blade\.php$/', $file, $matches)) {
                    $layoutName = $matches[1];
                    // Remove special characters like ⚡ for the name value
                    $cleanName = preg_replace('/[^\w\-]/', '', $layoutName);
                    // Create a readable label
                    $label = ucfirst(str_replace(['_', '-'], ' ', $cleanName));

                    $layouts[] = [
                        'name' => $cleanName,
                        'label' => $label,
                        'file' => $file,
                    ];
                }
            }
        }

        return ApiResponse::make(null, $layouts);
    }
}
