<?php

namespace App\Http\Controllers\DocumentManagement;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DocumentManagement;
use App\Models\VoucherType;

class DocumentsManagementController extends Controller
{
    function __construct()
    {
        
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('DOCUMENT_MANAGEMENT')) {
            abort(404);
        }

        $data = DocumentManagement::query();

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

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

            return view('documents-management.table', compact('data'));
        }
        else
        {
            $voucher_type = VoucherType::select('name','code')->where(['status' => 1])->get();
            $data = $data->paginate(10);

            return view('documents-management.index',compact('data','voucher_type'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $account_id = $request->account ?? '';
        $voucher    = $request->voucher ?? '';

        $voucher_type = VoucherType::select('name','code')->where(['status' => 1])->get();
        $priority     = DocumentManagement::max('priority');
        $priority     = $priority != '' ? $priority + 1 : 1;

        return view('documents-management.create', compact('priority', 'voucher_type', 'account_id', 'voucher'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'priority'     => 'required',
            'attachment'   => 'required',
            'voucher_type' => '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());
        }

        $data = $request->except([
            '_token',
            '_method',
            'attachment'
        ]);

        $voucher_type = VoucherType::with('voucherSeries')->where('code', $request->voucher_type)->where(['status' => 1])->first();

        # last voucher count for main voucher type invoice number
        $voucher_type_last_count = DocumentManagement::select('last_voucher_count')
            ->where(['voucher_type' => $request->voucher_type])
            ->orderBy('created_at', 'DESC')
            ->first();

        $voucher_type_count = isset($voucher_type_last_count) && isset($voucher_type_last_count->last_voucher_count) ? $voucher_type_last_count->last_voucher_count + 1 : ($voucher_type->voucherSeries->start_from + 1 ?? 1);

        $voucher_type_invoice_no = $this->generateCode(
            $voucher_type_count,
            ($voucher_type->voucherSeries->prefix ?? 'RV'),
            ($voucher_type->voucherSeries->postfix ?? ''),
            ($voucher_type->voucherSeries->separator ?? '-'),
            ($voucher_type->voucherSeries->length ?? 5)
        );

        $data['document_no'] = $voucher_type_invoice_no;

        if ($request->hasFile('attachment')) {
            $path     = 'document-management/' . date('Y') . '/' . date('M');
            $response = uploadImage($path, $request->attachment);

            if ($response['status'] == true) {
                $data['file_url'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        $default_check = DocumentManagement::where(['is_default' => '1','status' => '1'])->first();

        if (!$default_check) {
            $data['is_default'] = "1";
        }

        $data['last_voucher_count'] = $voucher_type_count;
        $data['voucher_id']         = $voucher_type->voucher_master_id;
        $data['company_id']         = \Auth::user()->company_id;
        $data['user_id']            = \Auth::id();
        $data['date_time']          = date('Y-m-d H:i:s');

        $document = DocumentManagement::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Document has been uploaded successfully.',
                'data'    => $document
            ]);
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $voucher_type = VoucherType::select('name','code')->where(['status' => 1])->get();
        $document     = DocumentManagement::find($id);

        return view('documents-management.edit', compact('document', 'voucher_type'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $document = DocumentManagement::find($id);

        if (!$document) {
            return response()->json([
                'success' => false,
                'message' => 'Document not found!',
                'data'    => []
            ]);
        }

        $validator = \Validator::make($request->all(), [
            'priority'     => 'required',
            // 'attachment'   => 'required',
            // 'voucher_type' => '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());
        }

        $data = $request->except([
            '_token',
            '_method',
            'document_no',
            'attachment'
        ]);

        if ($request->hasFile('attachment')) {
            $path     = 'document-management/' . date('Y') . '/' . date('M');
            $response = uploadImage($path, $request->attachment, $document->file_url);

            if ($response['status'] == true) {
                $data['file_url'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }

        $document = $document->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Document has been uploaded successfully.',
                'data'    => $document
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $account = DocumentManagement::find($request->id);

        /*if ($account->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }*/

        $account->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
            ]
        ]);
    }

   public function changedefault(Request $request)
   {
       if ($request->ajax())
       {
            $data  = array('is_default' => $request->status );
            $count = DocumentManagement::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Document!'],
                    'data'    => []
                ]);
            }

           $Update = DocumentManagement::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Document default status successfully change'],
                   'data'=>[
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
   }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = DocumentManagement::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Document status successfully change'],
                    'data'=>[
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
}
