<?php

namespace App\Http\Controllers\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\VoucherType;
use App\Models\OrganizationDepartment;
use App\Models\DepartmentClearanceSetting;

class ClearanceSettingsController extends Controller
{
    /**
     * Display a listing of the clearance settings.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function clearanceSettingsIndex(Request $request, $id)
    {
        // Fetch organization departments with their associated clearance settings
        $data = OrganizationDepartment::select([
            'organization_departments.name as organization_department_name',
            'department_clearance_settings.id' ,
        ])
        ->leftJoin('department_clearance_settings', 'department_clearance_settings.department_id', '=', 'organization_departments.id')
        ->leftJoin('voucher_types', 'department_clearance_settings.voucher_type_code', '=', 'voucher_types.code')
        ->where('voucher_types.id', $id);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby', 10);
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('organization_departments.name', 'like', '%' . $search_query . '%');
            })->paginate($sort_by);

            return view('voucher-types.clearance-settings.table', compact('data'))->render();
        } else {
            $voucher_type = VoucherType::find($id);
            $data         = $data->orderBy('organization_departments.name', 'ASC')->paginate(10);
            return view('voucher-types.clearance-settings.index', compact('data', 'id' , 'voucher_type'));
        }
    }

    /**
     * Show the form for creating a new clearance setting.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function createClearanceSettings($id = '')
    {
        $departments = OrganizationDepartment::leftJoin('department_clearance_settings' , 'department_clearance_settings.department_id' , '=' , 'organization_departments.id')
            ->whereNull('department_clearance_settings.department_id')
            ->select('organization_departments.*')
            ->get();


        return view('voucher-types.clearance-settings.create', compact('departments', 'id'));
    }

    /**
     * Store a newly created clearance setting.
     *
     * @param  Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeClearanceSettings(Request $request , $id = '')
    {
        $validator = \Validator::make($request->all(), [
             'department_id' => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $voucher_type = VoucherType::find($id);

        DepartmentClearanceSetting::create([
            'department_id'     => $request->department_id,
            'voucher_type_code' => $voucher_type->code,
        ]);


        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Clearance Settings Created Successfully',
            ]);

        return redirect()->route('clearance-settings.index')
            ->with('success', 'Clearance Settings Created Successfully.');
        }


    }

    /**
     * Delete a clearance setting.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deleteClearanceSettings($id)
    {
        $data = DepartmentClearanceSetting::find($id)->delete();

        return response()->json([
                        'success' => true,
                        'message' => 'Clearance Settings Deleted Successfully',
        ]);
    }
}
