<?php

namespace App\Http\Controllers;

use App\Models\PoslajuSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PoslajuSettingsController extends Controller
{
    /**
     * Display Poslaju settings form
     */
    public function index()
    {
        $settings = auth()->user()->poslajuSetting;

        return view('poslaju-settings.index', compact('settings'));
    }

    /**
     * Update Poslaju settings
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            // OAuth 2.0 Credentials
            'app_code' => 'required|string|max:255',
            'secret_code' => 'required|string|max:255',
            'client_id' => 'required|string|max:255',
            'client_secret' => 'required|string|max:255',
            // Deprecated fields (kept for backward compatibility)
            'api_key' => 'nullable|string|max:255',
            'secret_key' => 'nullable|string|max:255',
            // Account info
            'account_number' => 'required|string|max:255',
            'poslaju_account_id' => 'required|string|max:255',
            // API Required Fields
            'product_code' => 'required|string|max:50',
            'subscription_code' => 'nullable|string|max:255',
            'item_type' => 'required|string|in:Parcel,Document,Merchandise',
            'service_level' => 'required|string|in:Standard,Express',
            'order_validity' => 'required|integer|min:7|max:30',
            'webhook_required' => 'boolean',
            // Sender info
            'sender_name' => 'required|string|max:255',
            'sender_phone' => 'required|string|max:255',
            'sender_address' => 'required|string|max:255',
            'sender_postcode' => 'required|string|max:10',
            'sender_city' => 'required|string|max:255',
            'sender_state' => 'required|string|max:255',
            // Logos
            'poslaju_logo' => 'nullable|image|mimes:jpeg,jpg,png|max:2048',
            'company_logo' => 'nullable|image|mimes:jpeg,jpg,png|max:2048',
            // Default settings
            'default_weight' => 'required|numeric|min:0.1|max:99.99',
            'default_dimension_l' => 'required|numeric|min:1',
            'default_dimension_w' => 'required|numeric|min:1',
            'default_dimension_h' => 'required|numeric|min:1',
            // Options
            'is_active' => 'boolean',
            'hide_product_names' => 'boolean',
            'test_mode' => 'boolean',
        ]);

        $settings = auth()->user()->poslajuSetting ?? new PoslajuSetting(['user_id' => auth()->id()]);

        // Handle Poslaju logo removal
        if ($request->has('remove_poslaju_logo') && $settings->poslaju_logo_path) {
            // Delete old logo
            if (Storage::disk('public')->exists($settings->poslaju_logo_path)) {
                Storage::disk('public')->delete($settings->poslaju_logo_path);
            }
            if (str_starts_with($settings->poslaju_logo_path, '/images/')) {
                $oldPath = public_path($settings->poslaju_logo_path);
                if (file_exists($oldPath)) {
                    unlink($oldPath);
                }
            }
            $validated['poslaju_logo_path'] = null;
        }

        // Handle Poslaju logo upload
        if ($request->hasFile('poslaju_logo')) {
            // Delete old logo if exists (check both old storage path and new public path)
            if ($settings->poslaju_logo_path) {
                // Old storage path
                if (Storage::disk('public')->exists($settings->poslaju_logo_path)) {
                    Storage::disk('public')->delete($settings->poslaju_logo_path);
                }
                // New public path
                if (str_starts_with($settings->poslaju_logo_path, '/images/')) {
                    $oldPath = public_path($settings->poslaju_logo_path);
                    if (file_exists($oldPath)) {
                        unlink($oldPath);
                    }
                }
            }

            // Create images directory if it doesn't exist
            $imagesPath = public_path('images');
            if (!file_exists($imagesPath)) {
                mkdir($imagesPath, 0755, true);
            }

            // Store the uploaded file
            $file = $request->file('poslaju_logo');
            $fileName = 'poslaju_' . time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file->getClientOriginalName());
            $file->move($imagesPath, $fileName);

            // Save relative path
            $validated['poslaju_logo_path'] = '/images/' . $fileName;
        }

        // Handle Company logo removal
        if ($request->has('remove_company_logo') && $settings->company_logo_path) {
            // Delete old logo
            if (Storage::disk('public')->exists($settings->company_logo_path)) {
                Storage::disk('public')->delete($settings->company_logo_path);
            }
            if (str_starts_with($settings->company_logo_path, '/images/')) {
                $oldPath = public_path($settings->company_logo_path);
                if (file_exists($oldPath)) {
                    unlink($oldPath);
                }
            }
            $validated['company_logo_path'] = null;
        }

        // Handle Company logo upload
        if ($request->hasFile('company_logo')) {
            // Delete old logo if exists (check both old storage path and new public path)
            if ($settings->company_logo_path) {
                // Old storage path
                if (Storage::disk('public')->exists($settings->company_logo_path)) {
                    Storage::disk('public')->delete($settings->company_logo_path);
                }
                // New public path
                if (str_starts_with($settings->company_logo_path, '/images/')) {
                    $oldPath = public_path($settings->company_logo_path);
                    if (file_exists($oldPath)) {
                        unlink($oldPath);
                    }
                }
            }

            // Create images directory if it doesn't exist
            $imagesPath = public_path('images');
            if (!file_exists($imagesPath)) {
                mkdir($imagesPath, 0755, true);
            }

            // Store the uploaded file
            $file = $request->file('company_logo');
            $fileName = 'company_' . time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file->getClientOriginalName());
            $file->move($imagesPath, $fileName);

            // Save relative path
            $validated['company_logo_path'] = '/images/' . $fileName;
        }

        $validated['is_active'] = $request->has('is_active');
        $validated['hide_product_names'] = $request->has('hide_product_names');
        $validated['test_mode'] = $request->has('test_mode');
        $validated['webhook_required'] = $request->has('webhook_required');

        $settings->fill($validated);
        $settings->save();

        return redirect()->route('poslaju-settings.index')
            ->with('success', 'Poslaju settings updated successfully!');
    }
}
