<?php

namespace App\Http\Controllers\Admin\Setting;

use App\Http\Controllers\Controller;
use App\Models\BusinessType;
use App\Models\CashInHand;
use App\Models\Setting;
use App\Models\SettingRule;
use App\Service\Setting\GeneralSetting;
use Illuminate\Http\Request;
use Inertia\Inertia;

class GeneralSettingController extends Controller
{
    public function general_setting()
    {
        $business = BusinessType::get();
        $rules = SettingRule::orderBy('id')->get(['id', 'rule_name', 'value']);

        return Inertia::render('Settings/GeneralSetting', compact('business', 'rules'));
    }

    public function rulesStore(Request $request)
    {
        $request->validate([
            'rules' => 'required|array',
            'rules.*.rule_name' => 'required|string|max:255',
            'rules.*.value' => 'nullable|string|max:500',
        ]);

        $rules = $request->input('rules', []);
        $isAdmin = (string) auth()->user()->role_id === '1';

        foreach ($rules as $item) {
            if (empty($item['rule_name'])) {
                continue;
            }
            if (! empty($item['id'])) {
                $rule = SettingRule::find($item['id']);
                if ($rule) {
                    $rule->update([
                        'rule_name' => $item['rule_name'],
                        'value' => $item['value'] ?? '',
                    ]);
                }
            } else {
                if (! $isAdmin) {
                    continue;
                }
                SettingRule::create([
                    'rule_name' => $item['rule_name'],
                    'value' => $item['value'] ?? '',
                ]);
            }
        }

        return response()->json(['success' => 'Rules saved successfully.']);
    }

    public function rulesDestroy(Request $request, $id)
    {
        if ((string) auth()->user()->role_id !== '1') {
            return response()->json(['message' => 'Only administrators can delete rules.'], 403);
        }

        SettingRule::where('id', $id)->delete();

        return response()->json(['success' => 'Rule deleted.']);
    }

    public function ruleValue(Request $request)
    {
        $name = $request->input('name') ?? $request->query('name');
        if (! $name) {
            return response()->json(['value' => null], 400);
        }
        $value = SettingRule::where('rule_name', $name)->value('value');

        return response()->json(['value' => $value]);
    }

    public function store_setting()
    {
        GeneralSetting::SettingSore(Request()->all());

        return response()->json(['success' => 'Setting update Successfully']);
    }

    public function store_cash_in_hand()
    {
        $data = request()->all();
        $cashInHand = CashInHand::where('location_id', auth()->user()->shop_id)->first();
        if ($cashInHand) {
            $cashInHand->update($data);

            return response()->json(['success' => 'Cash In Hand updated successfully']);
        } else {
            CashInHand::create($data);

            return response()->json(['success' => 'Cash In Hand created successfully']);
        }
    }

    public function cash_in_hand()
    {

        $cashInHand = CashInHand::where('location_id', auth()->user()->shop_id)->first();
        $settings = Setting::first();

        return response()->json([
            'cashInHand' => $cashInHand,
            'settings' => $settings,
        ]);
    }

    public function settingUpdate()
    {
        $data = request()->all();

        if (isset($data['amount'])) {
            $cashInHand = CashInHand::where('location_id', auth()->user()->shop_id)->first();
            if ($cashInHand) {
                $cashInHand->update(['amount' => $data['amount']]);
            } else {
                CashInHand::create(['amount' => $data['amount']]);
            }
        }

        $setting = Setting::first();
        $updateData = [];

        if (isset($data['businessType'])) {
            $updateData['business_id'] = $data['businessType'];
        }

        if (isset($data['discountPercent'])) {
            $updateData['discount_percent'] = $data['discountPercent'];
        }

        // Shop Info Fields
        if (isset($data['shopName'])) {
            $updateData['shop_name'] = $data['shopName'];
        }
        if (isset($data['shopOwner'])) {
            $updateData['shop_owner'] = $data['shopOwner'];
        }
        if (isset($data['shopSlogan'])) {
            $updateData['shop_slogan'] = $data['shopSlogan'];
        }
        if (isset($data['shopBusinessType'])) {
            $updateData['shop_business_type'] = $data['shopBusinessType'];
        }
        if (isset($data['shopAddress'])) {
            $updateData['shop_address'] = $data['shopAddress'];
        }
        if (isset($data['shopPhone'])) {
            $updateData['shop_phone'] = $data['shopPhone'];
        }
        if (isset($data['shopEmail'])) {
            $updateData['shop_email'] = $data['shopEmail'];
        }
        if (isset($data['shopTaxId'])) {
            $updateData['shop_tax_id'] = $data['shopTaxId'];
        }
        if (isset($data['shopRegistrationNo'])) {
            $updateData['shop_registration_no'] = $data['shopRegistrationNo'];
        }
        if (isset($data['shopLogo'])) {
            $updateData['shop_logo'] = $data['shopLogo']; // Base64 encoded image
        }

        // Invoice Defaults Fields
        if (isset($data['invoiceCurrencySymbol'])) {
            $updateData['invoice_currency_symbol'] = $data['invoiceCurrencySymbol'];
        }
        if (isset($data['invoiceFooterNote'])) {
            $updateData['invoice_footer_note'] = $data['invoiceFooterNote'];
        }
        if (isset($data['invoicePrintMode'])) {
            $updateData['invoice_print_mode'] = $data['invoicePrintMode'];
        }

        // Sidebar Mode
        if (isset($data['sidebarMode'])) {
            $updateData['sidebar_mode'] = $data['sidebarMode'];
        }

        if (! empty($updateData)) {
            if (! $setting) {
                Setting::create($updateData);
            } else {
                $setting->update($updateData);
            }
        }

        return response()->json(['success' => 'Settings updated successfully']);

    }

    public function general_get()
    {
        return response()->json(['setting' => Setting::first()]);
    }

    public function getShopName()
    {
        $setting = Setting::first();

        return response()->json([
            'shop_name' => $setting?->shop_name ?? 'Demo Shop',
        ]);
    }
}
