<?php

namespace Modules\PurchaseRequisition\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\PurchaseRequisition\Entities\PrSetting;
use Modules\PurchaseRequisition\Entities\PrCurrency;
use Yajra\DataTables\Facades\DataTables;
use App\User;
use DB;

class PrSettingsController extends Controller
{

    /**
     * Display settings page.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');

        // Get current settings
        $settings = PrSetting::getSettings($businessId);

        // Get currencies
        $currencies = PrCurrency::forBusiness($businessId)->active()->get();

        return view('purchaseRequisition::settings.index', compact('settings', 'currencies'));
    }

    /**
     * Store settings.
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'selling_interval' => 'required|integer|min:1',
            'stock_cover_interval' => 'required|integer|min:1',
            'margin_ratio' => 'required|numeric|min:0',
            'avg_cost_period' => 'nullable|in:all,year_ago',
            'bg_color_no_purchase' => 'nullable|string',
            'bg_color_no_purchase_no_stock' => 'nullable|string',
            'bg_color_zero_qty' => 'nullable|string',
            'bg_color_low_margin' => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            $businessId = request()->session()->get('user.business_id');

            $settingsData = [
                'selling_interval' => $request->selling_interval,
                'stock_cover_interval' => $request->stock_cover_interval,
                'margin_ratio' => $request->margin_ratio,
                'avg_cost_period' => $request->avg_cost_period ?? 'all',
                'bg_color_no_purchase' => $request->bg_color_no_purchase ?? '#FFF3CD',
                'bg_color_no_purchase_no_stock' => $request->bg_color_no_purchase_no_stock ?? '#FFDDC1',
                'bg_color_zero_qty' => $request->bg_color_zero_qty ?? '#D1ECF1',
                'bg_color_low_margin' => $request->bg_color_low_margin ?? '#F8D7DA',
            ];

            PrSetting::updateSettings($businessId, $settingsData);

            DB::commit();

            $output = [
                'success' => 1,
                'msg' => __('purchaseRequisition::lang.updated_success')
            ];
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

            $output = [
                'success' => 0,
                'msg' => __('messages.something_went_wrong')
            ];
        }

        return redirect()->back()->with('status', $output);
    }

    /**
     * Get currencies for DataTable.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCurrencies(Request $request)
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        if ($request->ajax()) {
            $businessId = request()->session()->get('user.business_id');

            $currencies = PrCurrency::forBusiness($businessId)
                ->select(['id', 'code', 'name', 'symbol', 'conversion_rate_to_egp', 'is_active']);

            return DataTables::of($currencies)
                ->addColumn('action', function ($row) {
                    $html = '<div class="btn-group">
                        <button type="button" class="btn btn-info dropdown-toggle btn-xs" data-toggle="dropdown" aria-expanded="false">
                            ' . __('messages.actions') . '
                            <span class="caret"></span>
                            <span class="sr-only">Toggle Dropdown</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                            <li>
                                <a href="#" class="edit-currency" data-id="' . $row->id . '">
                                    <i class="glyphicon glyphicon-edit"></i> ' . __('messages.edit') . '
                                </a>
                            </li>
                            <li>
                                <a href="#" class="delete-currency" data-id="' . $row->id . '">
                                    <i class="glyphicon glyphicon-trash"></i> ' . __('messages.delete') . '
                                </a>
                            </li>
                        </ul>
                    </div>';
                    return $html;
                })
                ->editColumn('is_active', function ($row) {
                    return $row->is_active ? '<span class="label label-success">' . __('purchaseRequisition::lang.active') . '</span>' : '<span class="label label-default">' . __('purchaseRequisition::lang.inactive') . '</span>';
                })
                ->editColumn('conversion_rate_to_egp', function ($row) {
                    return number_format($row->conversion_rate_to_egp, 4);
                })
                ->rawColumns(['action', 'is_active'])
                ->make(true);
        }
    }

    /**
     * Store or update currency.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storeCurrency(Request $request)
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'code' => 'required|string|max:10',
            'name' => 'required|string|max:100',
            'symbol' => 'required|string|max:10',
            'conversion_rate_to_egp' => 'required|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        try {
            DB::beginTransaction();

            $businessId = request()->session()->get('user.business_id');

            $data = [
                'business_id' => $businessId,
                'code' => strtoupper($request->code),
                'name' => $request->name,
                'symbol' => $request->symbol,
                'conversion_rate_to_egp' => $request->conversion_rate_to_egp,
                'is_active' => $request->is_active ?? true,
            ];

            if ($request->id) {
                $currency = PrCurrency::findOrFail($request->id);
                $currency->update($data);
            } else {
                PrCurrency::create($data);
            }

            DB::commit();

            $output = [
                'success' => true,
                'msg' => __('purchaseRequisition::lang.added_success')
            ];
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

            $output = [
                'success' => false,
                'msg' => __('messages.something_went_wrong')
            ];
        }

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

    /**
     * Delete currency.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteCurrency($id)
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            DB::beginTransaction();

            $currency = PrCurrency::findOrFail($id);
            $currency->delete();

            DB::commit();

            $output = [
                'success' => true,
                'msg' => __('purchaseRequisition::lang.deleted_success')
            ];
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

            $output = [
                'success' => false,
                'msg' => __('messages.something_went_wrong')
            ];
        }

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

    /**
     * Get users for DataTable.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function indexUsers(Request $request)
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        if ($request->ajax()) {
            $businessId = request()->session()->get('user.business_id');

            $users = User::where('business_id', $businessId)
                ->select(['id', 'username', 'first_name', 'last_name', 'email']);

            return DataTables::of($users)
                ->addColumn('full_name', function ($row) {
                    return $row->first_name . ' ' . $row->last_name;
                })
                ->addColumn('role', function ($row) {
                    return $row->roles->pluck('name')->implode(', ');
                })
                ->addColumn('has_access', function ($row) {
                    $hasAccess = $row->can('purchase_requisition.access_module');
                    $checked = $hasAccess ? 'checked' : '';
                    return '<input type="checkbox" class="toggle-user-access" data-user-id="' . $row->id . '" ' . $checked . '>';
                })
                ->rawColumns(['has_access'])
                ->make(true);
        }
    }

    /**
     * Toggle user module access.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggleUserAccess(Request $request)
    {
        if (!auth()->user()->can('purchase_requisition.access_settings')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            $user = User::findOrFail($request->user_id);
            $hasAccess = $request->has_access == '1' || $request->has_access === true;

            // Get all PR permissions
            $prPermissions = \Spatie\Permission\Models\Permission::where('name', 'LIKE', 'purchase_requisition.%')->pluck('name')->toArray();

            if ($hasAccess) {
                // Give all PR permissions
                foreach ($prPermissions as $permission) {
                    if (!$user->hasPermissionTo($permission)) {
                        $user->givePermissionTo($permission);
                    }
                }
            } else {
                // Remove all PR permissions
                foreach ($prPermissions as $permission) {
                    if ($user->hasPermissionTo($permission)) {
                        $user->revokePermissionTo($permission);
                    }
                }
            }

            return response()->json([
                'success' => true,
                'msg' => __('purchaseRequisition::lang.updated_success')
            ]);
        } catch (\Exception $e) {
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

            return response()->json([
                'success' => false,
                'msg' => __('messages.something_went_wrong')
            ]);
        }
    }

}
