<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Lib\FormProcessor;
use App\Models\Admin;
use App\Models\Department;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    public function list()
    {
        $pageTitle   = 'Departments';
        $departments = Department::with('createdBy');

        if (request()->admin) {
            $departments->whereHas('admins', function ($admin) {
                $admin->where('admin_id', request()->admin);
            });
        }

        $departments = $departments->orderBy('id', 'desc')->get();

        return view('admin.setting.department.list', compact('pageTitle', 'departments'));
    }

    public function add()
    {
        $pageTitle = 'Add Department';
        return view('admin.setting.department.form', compact('pageTitle'));
    }

    public function edit($id)
    {
        $pageTitle  = 'Edit Department';
        $department = Department::findOrFail($id);
        return view('admin.setting.department.form', compact('pageTitle', 'department'));
    }

    public function save(Request $request, $id = 0)
    {
        $validationRule = [
            'name'        => 'required|unique:departments,name,' . $id . ',id',
            'description' => 'nullable',
            'email'       => 'nullable|email',
        ];

        if ($request->pipe_only) {
            $validationRule['host']           = 'required|string';
            $validationRule['port']           = 'required|string';
            $validationRule['email_user']     = 'required|string';
            $validationRule['email_password'] = 'required|string';
        }

        $request->validate($validationRule, ['name.unique' => 'Department already exists']);

        if ($id) {
            $department = Department::findOrFail($id);
            $message    = 'Department updated successfully';
        } else {
            $department                   = new Department();
            $department->admin_id         = auth('admin')->id();
            $department->last_inbox_check = today();
            $message                      = 'Department added successfully';
        }

        $department->name             = $request->name;
        $department->slug             = slug($request->name);
        $department->description      = $request->description;
        $department->email            = $request->email;
        $department->agents_only      = $request->agents_only ? 1 : 0;
        $department->pipe_only        = $request->pipe_only ? 1 : 0;
        $department->auto_respond     = $request->auto_respond ? 1 : 0;
        $department->auto_close       = $request->auto_close ? 1 : 0;
        $department->feedback_request = $request->feedback_request ? 1 : 0;

        if ($request->pipe_only) {
            $department->host           = $request->host;
            $department->port           = $request->port;
            $department->email_user     = $request->email_user;
            $department->email_password = $request->email_password;
        }

        $department->save();
        $notify[] = ['success', $message];

        if (!$id && !$department->pipe_only) {
            $admins = Admin::where('super_admin', Status::YES)->get();
            $department->admins()->attach($admins);

            $notify[] = ['info', 'You can add a custom field visible during ticket creation.'];
            return to_route('admin.department.form.builder', $department->id)->withNotify($notify);
        }

        return back()->withNotify($notify);
    }

    public function status($id)
    {
        $department = Department::find($id);

        if (!$department) {
            return response()->json([
                'status'  => 'error',
                'message' => 'No department found',
            ]);
        }

        $department->status = !$department->status;
        $department->save();

        $message = $department->status ? 'Department enabled successfully' : 'Department disabled successfully';

        return response()->json([
            'status'     => 'success',
            'message'    => $message,
            'department' => $department,
        ]);
    }

    public function formBuilder($id)
    {
        $pageTitle  = 'Form Builder';
        $department = Department::with('form')->findOrFail($id);
        if ($department->pipe_only) {
            abort(404);
        }
        return view('admin.setting.department.form_builder', compact('pageTitle', 'department'));
    }

    public function saveFormBuilder(Request $request, $id)
    {
        $department = Department::with('form')->findOrFail($id);

        $formProcessor       = new FormProcessor();
        $generatorValidation = $formProcessor->generatorValidation();
        $request->validate($generatorValidation['rules'], $generatorValidation['messages']);
        $formProcessor->generate('department', $department->form, 'department_id', $department->id);

        $notify[] = ['success', 'Form builder data updated successfully'];
        return back()->withNotify($notify);
    }

}
