<?php

namespace App\Modules\Admin\controllers;

use App\Http\Controllers\BaseController;
use App\Modules\Admin\DashboardTabSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardTabsController extends BaseController
{
    /**
     * The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Display the dashboard tabs settings page
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $tabs = DashboardTabSetting::getAllTabsOrdered();

        $this->layout->content = \View::make('admin::settings.dashboard-tabs.index', compact('tabs'));
    }

    /**
     * Update all tabs at once (labels and visibility)
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateAll(Request $request)
    {
        $tabs = $request->input('tabs', []);

        foreach ($tabs as $id => $data) {
            $tab = DashboardTabSetting::findOrFail($id);
            $tab->tab_label = $data['tab_label'];
            $tab->is_visible = isset($data['is_visible']) ? true : false;
            $tab->save();
        }

        return redirect()->route('admin.dashboard-tabs.index')
            ->with('success', 'Dashboard tabs updated successfully');
    }

    /**
     * Reset all tabs to default labels and visibility
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function resetToDefault()
    {
        // Default configuration with order
        $defaults = [
            'my_tasks' => ['label' => 'My Tasks', 'order' => 1],
            'repairs' => ['label' => 'Repairs', 'order' => 2],
            'remote_support' => ['label' => 'Remote Support', 'order' => 3],
            'onsite' => ['label' => 'Onsite', 'order' => 4],
            'delegated' => ['label' => 'Delegated', 'order' => 5],
            'sale_leads' => ['label' => 'Sale Leads', 'order' => 6],
            'rma' => ['label' => 'RMA', 'order' => 7],
            'projects' => ['label' => 'Projects', 'order' => 8],
            'my_completed' => ['label' => 'My Completed', 'order' => 9],
            'holidays_calendar' => ['label' => 'Holiday Calendar', 'order' => 10],
            'calendar' => ['label' => 'Calendar', 'order' => 11]
        ];

        // Update all tabs
        foreach ($defaults as $key => $data) {
            DashboardTabSetting::where('tab_key', $key)->update([
                'tab_label' => $data['label'],
                'is_visible' => true,
                'order_index' => $data['order']
            ]);
        }

        return redirect()->route('admin.dashboard-tabs.index')
            ->with('success', 'Dashboard tabs reset to default successfully');
    }
}
