<?php

namespace App\Http\Controllers\Accounts;

use Illuminate\Http\Request;
use App\Models\AccountAttachment;
use App\Http\Controllers\Controller;

class AccountAttachmentsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:account-attachments-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        return view('account-attachments.create', compact('id'));
    }

    /**
     * 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(), [
            'account_id' => 'required',
            'title'      => 'required',
            'file'       => 'required|mimes:jpg,jpeg,png,doc,docx,pdf',
        ]);

        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',
            'file'
        ]);
        $data['expiry_date'] = $request->expiry_date != '' ? date('Y-m-d', strtotime($request->expiry_date)) : '';

        if ($request->hasFile('file')) {
            $path     = 'account-attachments/' . date('Y') . '/' . date('M');
            $response = uploadImage($path,$request->file);

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

        AccountAttachment::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Account Attachment has been created successfully',
            ]);
        }

        return redirect()->back()
            ->with('success','Account Attachment has been created successfully');
    }

    /**
     * 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)
    {
        $attachment = AccountAttachment::find($id);

        return view('account-attachments.edit', compact('attachment'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'title' => 'required',
            'file'  => 'mimes:jpg,jpeg,png,doc,docx,pdf',
        ]);

        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',
            'file'
        ]);

        $attachment = AccountAttachment::find($id);

        if (!$attachment) {
            return redirect()->back()
                ->with('error','Address Attachment not found!');
        }

        $file_name = $attachment->file_name ?? '';

        if ($request->hasFile('file')) {
            $path     = 'account-attachments/' . date('Y') . '/' . date('M');
            $response = uploadImage($path,$request->file,$file_name);

            if ($response['status'] == true) {
                $data['file_name'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }
        $data['expiry_date'] = $request->expiry_date != '' ? date('Y-m-d', strtotime($request->expiry_date)) : '';

        $attachment->update($data);


        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Account Attachment has been updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Account Attachment has been updated successfully');
    }

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

        if ($attachment->file_name != '' && file_exists('uploads/account-attachments/' . $attachment->file_name)) {
            unlink('uploads/account-attachments/' . $attachment->file_name);
        }

        $attachment->delete();

        $Redirect = 'accounts';

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

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

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