<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\DocumentTracker;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class DocumentTrackerController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        //
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $data = DocumentTracker::with([
            'employee:employee_id,firstname,lastname',
            'sent_to:employee_id,firstname,lastname',
            'supporting_document:id,module_name'
        ])->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('document_id', 'like', '%' . $keyword . '%');
        })->where('employee_id', $user->employee_id)
        ->orWhere('send_to', $user->employee_id);

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $validator = Validator::make($request->all(), [
            'send_to' => "required",
            'document_id' => "required",
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        if($request->hasFile('attachment')) {
            $image      = $request->file('attachment');
            $attachment_name  = time().'_'.$image->getClientOriginalName();
            $path       = "document-tracker/".$attachment_name;
            if(Storage::disk('local')->put($path, file_get_contents($image)))
            {
                DB::connection()->beginTransaction();
                try {
                    $Status = DocumentTracker::create([
                        'employee_id' => $user->employee_id,
                        'send_to' => $request->send_to,
                        'document_id' => $request->document_id,
                        'remarks' => $request->remarks,
                        'attachment' => $attachment_name,
                    ]);

                    DB::connection()->commit();

                    return response()->json([
                        'status'  => true,
                        'message' => 'Saved successfully!',
                        'data'    => $Status
                    ],201);

                } catch (Throwable $e) {

                    DB::connection()->rollback();
                    return response()->json([
                        'status'  => false,
                        'message' => 'Unable to process request. Please try again.',
                        'data'    => $e->getMessage()
                    ]);
                }
            }
            else
            {
                return response()->json([
                    'status'  => false,
                    'message' => 'Unable to process request. Please try again.',
                    'data'    => $e->getMessage()
                ]);
            }
        }
    }

    public function update(Request $request)
    {
        // dd($request->all());
        $id = $request->id;

        $user = Auth::user();

        $data = DocumentTracker::where('id', $id)->first();
        
        $validator = Validator::make($request->all(), [
            'send_to' => "required",
            'document_id' => "required",
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $attachment_name = $request->attachment;

        if($data->attachment != $request->attachment)
        {
            $attachment_file_path = 'document-tracker/' . $data->attachment;
            if(Storage::exists($attachment_file_path))
            {
                Storage::delete($attachment_file_path);
            }

            if($request->hasFile('attachment')) {
                $image      = $request->file('attachment');
                $attachment_name  = time().'_'.$image->getClientOriginalName();
                $path       = "document-tracker/".$attachment_name;
                if(!Storage::disk('local')->put($path, file_get_contents($image)))
                {
                    return response()->json(['message'=> "Failed to upload attachment"],304);
                }
            }
            else
            {
                $attachment_name = null;
            }
        }

        DB::connection()->beginTransaction();

        try {
            $data->employee_id = $user->employee_id;
            $data->send_to = $request->send_to;
            $data->document_id = $request->document_id;
            $data->remarks = $request->remarks;
            $data->attachment = $attachment_name;
            $data->save();
            
            DB::connection()->commit();

            return response()->json([
                'status'  => true,
                'message' => 'Saved successfully!',
                'data'    => $data
            ],201);

        } catch (Throwable $e) {

            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        } 
    }

    public function destroy(int $id)
    {
        $data = DocumentTracker::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }
}
