<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class SettingsController extends Controller
{
    /**
     * Display system settings.
     *
     * Both Admin and Staff can VIEW settings.
     * Only Admin can UPDATE them.
     */
    public function index()
    {
        $settingsRow = DB::table('settings')->first();

        if ($settingsRow) {
            $settings = [
                'business_name' => $settingsRow->business_name,
                'owner_name' => $settingsRow->owner_name,
                'business_email' => $settingsRow->email,
                'business_phone' => $settingsRow->phone,

                'default_order_status' => $settingsRow->default_order_status,
                'low_stock_alert' => $settingsRow->low_stock_alert,

                'notify_low_stock' => $settingsRow->notify_low_stock,
                'notify_new_order' => $settingsRow->notify_new_order,
                'notify_payment' => $settingsRow->notify_payment,
            ];
        } else {
            $settings = [
                'business_name' => 'Z&T Stationery Distribution',
                'owner_name' => '',
                'business_email' => '',
                'business_phone' => '',

                'default_order_status' => 'Pending',
                'low_stock_alert' => 10,

                'notify_low_stock' => 1,
                'notify_new_order' => 1,
                'notify_payment' => 1,
            ];
        }

        return view('settings/setting', compact('settings'));
    }

    /**
     * Update system settings.
     *
     * ONLY ADMIN is allowed to perform this action.
     */
    public function update(Request $request)
    {
        /*
        |--------------------------------------------------------------------------
        | ADMIN ONLY
        |--------------------------------------------------------------------------
        */

        $user = Auth::user();

        if (!$user || !$this->isAdmin($user)) {
            abort(403, 'Unauthorized. Only administrators can update system settings.');
        }

        /*
        |--------------------------------------------------------------------------
        | VALIDATION
        |--------------------------------------------------------------------------
        */

        $request->validate([
            'business_name' => 'nullable|string|max:255',
            'owner_name' => 'nullable|string|max:255',
            'business_email' => 'nullable|email|max:255',
            'business_phone' => 'nullable|string|max:50',

            'default_order_status' => 'required|in:Pending,Processing,Completed,Cancelled',

            'low_stock_alert' => 'required|integer|min:0',

            'change_password' => 'nullable|string|min:6',
            'confirm_password' => 'nullable|same:change_password',
        ]);

        /*
        |--------------------------------------------------------------------------
        | SAVE SETTINGS
        |--------------------------------------------------------------------------
        */

        DB::table('settings')->updateOrInsert(
            ['id' => 1],
            [
                'business_name' => $request->business_name,
                'owner_name' => $request->owner_name,
                'email' => $request->business_email,
                'phone' => $request->business_phone,

                'default_order_status' => $request->default_order_status,

                'low_stock_alert' => $request->low_stock_alert,

                'notify_low_stock' => $request->has('notify_low_stock') ? 1 : 0,

                'notify_new_order' => $request->has('notify_new_order') ? 1 : 0,

                'notify_payment' => $request->has('notify_payment') ? 1 : 0,

                'updated_at' => now(),

                /*
                |--------------------------------------------------------------------------
                | Do not overwrite created_at unnecessarily
                |--------------------------------------------------------------------------
                */

                'created_at' => DB::raw('COALESCE(created_at, NOW())'),
            ]
        );

        /*
        |--------------------------------------------------------------------------
        | CHANGE ADMIN PASSWORD
        |--------------------------------------------------------------------------
        */

        if ($request->filled('change_password')) {
            Auth::user()->update([
                'password' => Hash::make($request->change_password),
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | REDIRECT
        |--------------------------------------------------------------------------
        */

        return redirect()
            ->route('settings')
            ->with('success', 'Settings updated successfully.');
    }

    /**
     * Check whether the logged-in user is an Admin.
     *
     * Supports the existing User -> Role relationship.
     */
    private function isAdmin($user)
    {
        $roleName = optional($user->role)->role_name;

        return strtolower(trim($roleName ?? '')) === 'admin';
    }
}