<?php

namespace App\Http\Controllers\Admin\Store;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\Setting;
use App\Models\Translation\SettingTranslation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class MontessoriPrintsController extends Controller
{
    public function index()
    {
        $this->authorize('admin_store_settings');

        removeContentLocale();

        // Clear cache first to ensure fresh data
        cache()->forget('settings.montessori_prints_settings');
        
        $setting = Setting::where('page', 'general')
            ->where('name', 'montessori_prints_settings')
            ->first();

        $settingValue = [];
        if (!empty($setting) && !empty($setting->value)) {
            $settingValue = is_string($setting->value) ? json_decode($setting->value, true) : $setting->value;
            if (!is_array($settingValue)) {
                $settingValue = [];
            }
        }

        // Get all products
        $allProducts = Product::where('status', Product::$active)
            ->orderBy('created_at', 'desc')
            ->get();

        // Get selected products
        $selectedProducts = [];
        if (!empty($settingValue['montessori_prints_products']) && is_array($settingValue['montessori_prints_products'])) {
            $selectedProducts = $settingValue['montessori_prints_products'];
        }

        // Get categories
        $categories = ProductCategory::whereNull('parent_id')
            ->with([
                'subCategories' => function ($query) {
                    $query->orderBy('order', 'asc');
                },
            ])
            ->get();

        // Get selected category (default to category_id 13)
        $selectedCategoryId = !empty($settingValue['montessori_prints_category_id']) ? $settingValue['montessori_prints_category_id'] : 13;

        // Get products per page
        $perPage = !empty($settingValue['montessori_prints_per_page']) ? (int)$settingValue['montessori_prints_per_page'] : 24;

        // Get status
        $status = !empty($settingValue['montessori_prints_status']) ? $settingValue['montessori_prints_status'] : 1;

        $data = [
            'pageTitle' => 'إدارة مطبوعات المنتسورى',
            'itemValue' => $settingValue,
            'allProducts' => $allProducts,
            'selectedProducts' => $selectedProducts,
            'categories' => $categories,
            'selectedCategoryId' => $selectedCategoryId,
            'perPage' => $perPage,
            'status' => $status,
        ];

        return view('admin.store.montessori_prints.index', $data);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_store_settings');

        $data = $request->all();
        $newValues = $data['value'] ?? [];

        $validator = Validator::make($newValues, [
            'montessori_prints_per_page' => 'nullable|integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $settings = Setting::where('name', 'montessori_prints_settings')->first();
        
        $values = [];

        if (!empty($settings) && !empty($settings->value)) {
            $values = json_decode($settings->value, true);
            if (!is_array($values)) {
                $values = [];
            }
        }

        // Handle status checkbox - always set it
        $statusValue = isset($newValues['montessori_prints_status']) && $newValues['montessori_prints_status'] == '1' ? 1 : 0;
        $values['montessori_prints_status'] = $statusValue;

        // Handle per page
        if (isset($newValues['montessori_prints_per_page']) && $newValues['montessori_prints_per_page'] !== '') {
            $values['montessori_prints_per_page'] = (int)$newValues['montessori_prints_per_page'];
        } else {
            // Keep existing value or set default
            if (!isset($values['montessori_prints_per_page'])) {
                $values['montessori_prints_per_page'] = 24;
            }
        }

        // Handle category
        if (isset($newValues['montessori_prints_category_id']) && $newValues['montessori_prints_category_id'] !== '') {
            $values['montessori_prints_category_id'] = (int)$newValues['montessori_prints_category_id'];
        } else {
            // Default to category_id 13 if not set
            $values['montessori_prints_category_id'] = 13;
        }

        // Handle products array - always set it, even if empty
        if (isset($newValues['montessori_prints_products']) && is_array($newValues['montessori_prints_products'])) {
            // Filter out empty values and convert to integers
            $products = array_filter($newValues['montessori_prints_products'], function($value) {
                return $value !== '' && $value !== null;
            });
            $values['montessori_prints_products'] = array_values(array_map('intval', $products));
        } else {
            $values['montessori_prints_products'] = [];
        }

        $jsonValue = json_encode($values);

        try {
            $locale = Setting::$defaultSettingsLocale;
            
            // First, create or update the setting record
            $setting = Setting::updateOrCreate(
                ['name' => 'montessori_prints_settings'],
                [
                    'page' => 'general',
                    'updated_at' => time(),
                ]
            );

            // Refresh to ensure we have the ID
            $setting->refresh();

            // Then, save the value in setting_translations table
            $translation = SettingTranslation::updateOrCreate(
                [
                    'setting_id' => $setting->id,
                    'locale' => mb_strtolower($locale)
                ],
                [
                    'value' => $jsonValue,
                ]
            );

            // Clear cache
            try {
                cache()->forget('settings.montessori_prints_settings');
            } catch (\Exception $cacheException) {
                Log::warning('Cache clear warning: ' . $cacheException->getMessage());
            }

            if ($setting && $translation) {
                return back()->with('msg', trans('admin/main.success_update'));
            } else {
                return back()->with('error', 'حدث خطأ أثناء الحفظ');
            }
        } catch (\Exception $e) {
            Log::error('MontessoriPrints Store Method Exception: ' . $e->getMessage());
            return back()->with('error', 'حدث خطأ: ' . $e->getMessage());
        }
    }
}

