<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SystemSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SystemSettingsController extends Controller
{
    /**
     * Get all system settings (admin only)
     */
    public function index(Request $request)
    {
        $user = $request->user();
        
        // Only allow admin and super_admin
        if (!$user || !in_array($user->role, ['admin', 'super_admin'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $settings = SystemSetting::getSettings();
        
        // Convert logo_path to full URL if it exists
        $data = $settings->toArray();
        if ($data['logo_path']) {
            $data['logo_url'] = url($data['logo_path']);
        } else {
            $data['logo_url'] = null;
        }

        return response()->json($data);
    }

    /**
     * Update system settings (admin only)
     */
    public function update(Request $request)
    {
        $user = $request->user();
        
        // Only allow admin and super_admin
        if (!$user || !in_array($user->role, ['admin', 'super_admin'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'company_name' => 'nullable|string|max:255',
            'company_email' => 'nullable|email|max:255',
            'company_phone' => 'nullable|string|max:50',
            'company_address' => 'nullable|string',
            'footer_phone' => 'nullable|string|max:50',
            'footer_email' => 'nullable|email|max:255',
            'footer_address' => 'nullable|string',
            'social_facebook' => 'nullable|url|max:255',
            'social_twitter' => 'nullable|url|max:255',
            'social_instagram' => 'nullable|url|max:255',
            'social_linkedin' => 'nullable|url|max:255',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $settings = SystemSetting::getSettings();

        // Handle logo upload
        if ($request->hasFile('logo')) {
            // Delete old logo if exists
            if ($settings->logo_path && file_exists(public_path($settings->logo_path))) {
                unlink(public_path($settings->logo_path));
            }

            // Ensure logos directory exists
            $logosDir = public_path('logos');
            if (!file_exists($logosDir)) {
                mkdir($logosDir, 0755, true);
            }

            // Store new logo in public/logos directory
            $file = $request->file('logo');
            $filename = 'system_logo_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move($logosDir, $filename);
            $validated['logo_path'] = 'logos/' . $filename;
        }

        // Remove logo from validated if not provided (don't update if not sent)
        if (!$request->hasFile('logo')) {
            unset($validated['logo']);
        }

        $settings->update($validated);

        // Return updated settings with logo_url
        $data = $settings->fresh()->toArray();
        if ($data['logo_path']) {
            $data['logo_url'] = url($data['logo_path']);
        } else {
            $data['logo_url'] = null;
        }

        return response()->json([
            'message' => 'Settings updated successfully',
            'data' => $data
        ]);
    }

    /**
     * Delete logo (admin only)
     */
    public function deleteLogo(Request $request)
    {
        $user = $request->user();
        
        // Only allow admin and super_admin
        if (!$user || !in_array($user->role, ['admin', 'super_admin'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $settings = SystemSetting::getSettings();

        // Delete logo file if exists
        if ($settings->logo_path && file_exists(public_path($settings->logo_path))) {
            unlink(public_path($settings->logo_path));
        }

        $settings->update(['logo_path' => null]);

        return response()->json([
            'message' => 'Logo deleted successfully',
            'data' => $settings->fresh()
        ]);
    }

    /**
     * Get footer data (public endpoint)
     */
    public function getFooter(Request $request)
    {
        $settings = SystemSetting::getSettings();
        $response = response()->json([
            'phone' => $settings->footer_phone,
            'email' => $settings->footer_email,
            'address' => $settings->footer_address,
            'social_facebook' => $settings->social_facebook,
            'social_twitter' => $settings->social_twitter,
            'social_instagram' => $settings->social_instagram,
            'social_linkedin' => $settings->social_linkedin,
        ]);
        return $response;
    }

    /**
     * Get system logo (public endpoint - for login, register, home pages)
     */
    public function getSystemLogo(Request $request)
    {
        $settings = SystemSetting::getSettings();
        $logo = null;
        
        // Get logo from system settings (admin-set logo)
        if ($settings->logo_path) {
            // Check if file exists
            $logoPath = public_path($settings->logo_path);
            if (file_exists($logoPath)) {
                $logo = url($settings->logo_path);
            }
        }
        
        // Fallback to logo_pandamart.png if system logo not set
        if (!$logo) {
            $fallbackLogo = 'logos/logo_pandamart.png';
            if (file_exists(public_path($fallbackLogo))) {
                $logo = url($fallbackLogo);
            } else {
                // Last fallback to azan_logo.jpg
                $defaultLogo = 'images/azan_logo.jpg';
                if (file_exists(public_path($defaultLogo))) {
                    $logo = url($defaultLogo);
                }
            }
        }
        
        $response = response()->json(['logo_url' => $logo]);
        return $response;
    }
}
