<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UserWarnign;
use Illuminate\Support\Facades\Validator;
use DB;
class WarningController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {
        // dd("hello"); // Debug statement commented out
        $id = 423;
        $data = DB::table('user_warnigns')
        ->leftJoin('emp_personal_details as authorised_by', 'user_warnigns.created_by', '=', 'authorised_by.emp_id')
        ->where('user_warnigns.created_by', "=", $id)
        ->select(
            'user_warnigns.*',
            'authorised_by.first_name as first_name',
            'authorised_by.last_name as last_name',)
        ->get();
        // dd($data); // Debug statement commented out
        return response()->json([
                'message' => 'Warning Saved Successfully',
                'data'   => $data
            ],200);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
       
    }

    /**
     * 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(), [
        //    'image' => 'required|mimes:jpeg,png,jpg,gif,pdf,doc,docx|max:6048',
        //     'description' => 'nullable|string',
        ]);


        if ($validator->fails()) {

            $errors = $validator->errors();

            return response()->json([
                'message' => 'Validation Failed',
                'data' => $errors
            ],422);


        } else {
            if ($request->hasFile('image') && $request->file('image')->isValid()) {
                $imageName = time() . '-' . $request->file('image')->getClientOriginalName();
                $imagePath = $request->file('image')->move(public_path('upload/user_warning'), $imageName);
                $image = new UserWarnign();
                $image->image = 'upload/user_warning/' . $imageName;
                $image->description = $request->description;
                $image->emp_id = $request->emp_id;
                $image->created_by = auth()->user()->id;
                $image->save();
                $images = UserWarnign::all();

                // $images = UserWarnign::where('whs_report_id', $request->whs_report_id)->get();
                return response()->json([
                'message' => 'Warning Data uploaded successfully!',
                'success' => 'Warning Data uploaded successfully!',
                'image_url' => asset('upload/user_warning/' . $imageName),
                'images' => $images,
                ]);
                }
                else 
                {
                    return response()->json([
                    'message' => 'No valid image uploaded.',
                    'error' => 'Invalid or no image uploaded.',
                    ], 400);
                }     
        }      
    }

    /**
     * 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)
    {
        //
        $UserWarnign = UserWarnign::where('id',$id)->get();
        return response()->json($UserWarnign);
    }

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        UserWarnign::where('id',$id)->delete();
        session()->flash('success', 'User Warning Deleted Successfully');
        return response()->json([
            'message' => 'Tier Deleted Successfully'
        ],200);
    }

    public function getUserWarning(Request $request)
    {
        
        $id = $request->id;
        $query = DB::table('user_warnigns')
        ->leftJoin('emp_personal_details as authorised_by', 'user_warnigns.created_by', '=', 'authorised_by.emp_id')
        ->where('user_warnigns.emp_id', "=", $id)
        ->select(
            'user_warnigns.*',
            'authorised_by.first_name as first_name',
            'authorised_by.last_name as last_name',);


        $count = $query->count();
        $start = $request->input('from', 0);
        $query->offset($start)->limit(10);
        $query->orderBy('id', 'desc');
        $data = $query->get();
        return response()->json([
                'message' => 'Warning Saved Successfully',
                'data'   => $data,
                'count'   => $count

            ],200);
    }

    public function UpdateUserWarning(Request $request)
    {
        
        $validator = Validator::make($request->all(), [
           
            'description' => 'nullable|string',
        ]);
        
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json([
                'message' => 'Validation Failed',
                'data' => $errors
            ], 422);
        } else {
            $id = $request->id;
            // Assuming you are passing 'id' to update an existing record
            $imageRecord = UserWarnign::find($id);
        
            if (!$imageRecord) {
                return response()->json([
                    'message' => 'Record not found.',
                    'error' => 'No record found with the given ID.',
                ], 404);
            }
        
            // If there's a new image
            if ($request->hasFile('image') && $request->file('image')->isValid()) {
                // Delete the old image if it exists
                if (file_exists(public_path($imageRecord->image))) {
                    unlink(public_path($imageRecord->image));
                }
        
                // Store the new image
                $imageName = time() . '-' . $request->file('image')->getClientOriginalName();
                $imagePath = $request->file('image')->move(public_path('upload/user_warning'), $imageName);
                $imageRecord->image = 'upload/user_warning/' . $imageName;
            }
        
            // Update other fields
            $imageRecord->description = $request->description ?? $imageRecord->description; // Use existing description if not provided
            $imageRecord->save();
            // Optionally, get all records or only the updated one
            $images = UserWarnign::all();
        
            return response()->json([
                'message' => 'Warning Data updated successfully!',
                'success' => 'Warning Data updated successfully!',
                'image_url' => asset('upload/user_warning/' . $imageRecord->image),
                'images' => $images,
            ]);
        }
    }
}
