<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\CompanyMedia;
use App\Helpers\CompanyProfileExtras;
use App\Helpers\CompanySettings;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PreferenceController extends AdminController
{
    public function general()
    {
        $company = Company::findOrFail($this->companyId());
        $settings = CompanySettings::forCompany($company->id);

        return view('admin.preferences.general', [
            'company' => $company,
            'settings' => $settings,
            'activeSection' => 'general',
        ]);
    }

    public function updateGeneral(Request $request)
    {
        $company = Company::findOrFail($this->companyId());
        $toggleKeys = collect(config('preferences.toggles', []))->pluck('key')->all();
        $defaultKeys = array_keys(config('preferences.defaults', []));

        $validated = $request->validate([
            'date_format' => ['required', 'string', 'max:30'],
            'decimal_places' => ['required', 'integer', 'in:0,1,2,3'],
            'quantity_decimal_places' => ['required', 'integer', 'in:0,1,2,3'],
            'document_prefix_separator' => ['required', 'string', 'max:5'],
            'primary_signature_label' => ['nullable', 'string', 'max:100'],
            'secondary_signature_label' => ['nullable', 'string', 'max:100'],
            'financial_year_end' => ['nullable', 'date'],
            'signature_image' => ['nullable', 'image', 'max:2048'],
            'remove_signature' => ['nullable', 'boolean'],
        ]);

        $settings = [
            'date_format' => $validated['date_format'],
            'decimal_places' => (int) $validated['decimal_places'],
            'quantity_decimal_places' => (int) $validated['quantity_decimal_places'],
            'document_prefix_separator' => $validated['document_prefix_separator'],
            'primary_signature_label' => $validated['primary_signature_label'] ?? 'Provider Signature',
            'secondary_signature_label' => $validated['secondary_signature_label'] ?? 'Receiver Signature',
        ];

        foreach ($toggleKeys as $key) {
            $settings[$key] = $request->boolean($key);
        }

        CompanySettings::update($company->id, $settings);

        $company->financial_year_end = $validated['financial_year_end'] ?? null;

        if ($request->boolean('remove_signature') && $company->signature_image_path) {
            Storage::disk('public')->delete($company->signature_image_path);
            $company->signature_image_path = null;
        }

        if ($request->hasFile('signature_image')) {
            if ($company->signature_image_path) {
                Storage::disk('public')->delete($company->signature_image_path);
            }
            $company->signature_image_path = $request->file('signature_image')
                ->store('signatures/'.$company->id, 'public');
            CompanyMedia::clearPdfImageCache();
        }

        $company->save();

        return redirect()->route('admin.preferences.general')
            ->with('success', 'Preferences saved successfully.');
    }

    public function profile()
    {
        $company = Company::findOrFail($this->companyId());

        if (! $company->address_line1 && $company->address) {
            $parts = preg_split("/\r\n|\n|\r/", $company->address);
            $company->address_line1 = $parts[0] ?? '';
            $company->address_line2 = $parts[1] ?? '';
        }

        return view('admin.preferences.profile', [
            'company' => $company,
            'activeSection' => 'company_profile',
            'extraFields' => CompanyProfileExtras::resolvedFields($company),
            'showExtraPanel' => CompanyProfileExtras::hasExtraContent($company)
                || old('extra_fields') !== null,
        ]);
    }

    public function updateProfile(Request $request)
    {
        $company = Company::findOrFail($this->companyId());

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'legal_name' => ['nullable', 'string', 'max:255'],
            'currency' => ['required', 'string', 'max:10'],
            'country' => ['required', 'string', 'max:100'],
            'state' => ['nullable', 'string', 'max:100'],
            'city' => ['nullable', 'string', 'max:100'],
            'address_line1' => ['nullable', 'string', 'max:255'],
            'address_line2' => ['nullable', 'string', 'max:255'],
            'pincode' => ['nullable', 'string', 'max:10'],
            'email' => ['nullable', 'email', 'max:255'],
            'website' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:20'],
            'contact_name' => ['nullable', 'string', 'max:255'],
            'taxation_type' => ['nullable', 'string', 'max:50'],
            'service_tax_no' => ['nullable', 'string', 'max:50'],
            'extra_fields' => ['nullable', 'array'],
            'extra_fields.*' => ['nullable', 'string', 'max:100'],
            'extra_fields.pan' => ['nullable', 'string', 'max:10'],
            'extra_fields.gstin' => ['nullable', 'string', 'max:15'],
            'bank_name' => ['nullable', 'string', 'max:255'],
            'bank_branch' => ['nullable', 'string', 'max:255'],
            'bank_account' => ['nullable', 'string', 'max:50'],
            'account_holder_name' => ['nullable', 'string', 'max:255'],
            'bank_ifsc' => ['nullable', 'string', 'max:20'],
            'bank_ad_code' => ['nullable', 'string', 'max:50'],
            'bank_swift' => ['nullable', 'string', 'max:50'],
            'bank_iban' => ['nullable', 'string', 'max:50'],
            'bank_sort_code' => ['nullable', 'string', 'max:20'],
            'upi_id' => ['nullable', 'string', 'max:100'],
            'company_logo' => ['nullable', 'image', 'max:2048'],
            'remove_logo' => ['nullable', 'boolean'],
        ]);

        $validated['tax_inclusive_rates'] = $request->boolean('tax_inclusive_rates');
        $validated['is_composition_scheme'] = $validated['taxation_type'] === 'registered_composition';

        $validated['address'] = trim(
            ($validated['address_line1'] ?? '')."\n".($validated['address_line2'] ?? '')
        );

        $extraInput = $request->input('extra_fields', []);
        if (isset($extraInput['pan'])) {
            $validated['pan'] = $extraInput['pan'];
        }
        if (isset($extraInput['gstin'])) {
            $validated['gstin'] = $extraInput['gstin'];
        }
        if (isset($extraInput['legal_name'])) {
            $validated['legal_name'] = $extraInput['legal_name'];
        }

        $company->fill(collect($validated)->except(['extra_fields'])->all());
        CompanyProfileExtras::persist($company, $request);

        if ($request->boolean('remove_logo') && $company->logo_path) {
            Storage::disk('public')->delete($company->logo_path);
            $company->logo_path = null;
            CompanyMedia::clearPdfImageCache();
        }

        if ($request->hasFile('company_logo')) {
            if ($company->logo_path) {
                Storage::disk('public')->delete($company->logo_path);
            }
            $company->logo_path = $request->file('company_logo')
                ->store('logos/'.$company->id, 'public');
            CompanyMedia::clearPdfImageCache();
        }

        $company->save();

        return redirect()->route('admin.preferences.profile')
            ->with('success', 'Company profile saved successfully.');
    }
}
