<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use DateTime;
use DatePeriod;
use DateInterval;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Mail\Mailable;
use App\Mail\DemoMail;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\{User,Location,Report};


class ApiController extends Controller
{


            public function login(Request $request)
            {
                 $messages = array(
                    'email.required' => 'Email is required',
                    'password.required' => 'password is required',

                );
                $validator = Validator::make($request->all(), [
                    'email' => 'required',
                    'password' => 'required',
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'result' => false,
                        'message' => $validator->errors()

                    ]);
                }

                $email = $request->input('email');
                $password = $request->input('password');

                if (Auth::attempt(['email' => $email, 'password' => $password])) {
                    $user = Auth::user(); 

                    if ($user->status == 0) {
                        return response()->json([
                            'status' => 'false',
                            'msg' => 'Your account is deactivated. Please contact the admin for reactivation.',
                        ], 200);
                    } else {
                        // User is successfully logged in
                        return response()->json([
                            'status' => 'true',
                            'msg' => 'User logged in successfully!',
                            'data' => $user,
                        ], 200);
                    }
                }

                // Check if the email is correct
                $user = User::where('email', $email)->first();

                if (!$user) {
                    return response()->json([
                        'status' => 'false',
                        'msg' => 'Incorrect email entered!',
                    ], 200);
                } else {
                    return response()->json([
                        'status' => 'false',
                        'msg' => 'Incorrect password entered!',
                    ], 200);
                }
            }


            public function userShow()
            {
                $users = User::where('status', 1)->get();

                if (!$users->isEmpty()) {
                    return response()->json([
                        'status' => 'true',
                        'msg' => 'All active users',
                        'data' => $users
                    ], 200);
                } else {
                    return response()->json([
                        'status' => 'false',
                        'msg' => 'No active users found',
                    ], 200);
                }
            }


            public function userShowid(Request $request)
            {
                $messages = array(
                    'user_id.required' => 'user id is required',

                );
                $validator = Validator::make($request->all(), [
                    'user_id' => 'required',
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'result' => false,
                        'message' => $validator->errors()

                    ]);
                }
                $user_id = $request->input('user_id');
                $user = User::find($user_id);

                if (!$user) {
                    return response()->json([
                        'status' => 'false',
                        'msg' => 'User not found',
                    ], 404); 
                }

                $formattedUser = [
                    'id' => $user->id,
                    'name' => $user->name,
                    'role' => $user->role,
                    'profile' => $user->profile,
                    'mobile' => $user->mobile,
                    'email' => $user->email,
                    'DOB' => $user->DOB,
                    'status' => $user->status,
                    'state' => $user->State->name,
                    'city' => $user->City->name,
                    'pincode' => $user->pincode,
                    'address' => $user->address,
                    'bank_details' => $user->bank_details,
                ];

                return response()->json([
                    'status' => 'true',
                    'msg' => 'User retrieved successfully.',
                    'data' => $formattedUser,
                ], 200);
            }

            

            public function Profile_Updated(Request $request)
            {
                $messages = array(
                    'user_id.required' => 'User ID is required',
                    'profile.required' => 'Profile is required',
                );

                $validator = Validator::make($request->all(), [
                    'user_id' => 'required',
                    'profile' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', 
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'result' => false,
                        'message' => $validator->errors()
                    ]);
                }

                $user_id = $request->input('user_id');
                $user = User::find($user_id);

                if (!$user) {
                    return response()->json([
                        'result' => false,
                        'message' => 'User not found'
                    ]);
                }

                if ($request->file('profile')) {
                    $file = $request->file('profile');
                    $filename = date('YmdHi') . $file->getClientOriginalName();
                    $file->move(public_path('public/Image'), $filename);
                    $params['profile'] = $filename;

                    $user->update($params);

                    return response()->json(['success' => 'Profile updated successfully'], 200);
                } else {
                    return response()->json(['error' => 'Something went wrong...'], 400);
                }
            }




            public function Location_Show()
            {
                $location = Location::where('status','1')->orderBy('created_at' ,'desc')->get();

                if ($location->isEmpty()) {
                    return response()->json(['status' => 'false','msg' => 'location not found.',], 200);
                } else
                {
                    return response()->json(['status' => 'true','msg' => 'All location retrieved successfully.','data' => $location,
                    ], 200);
                }
            }




            public function Complain_Show(Request $request)
            {


                $this->validate($request,[
                'user_id'=>'required'
                ]);

                $user_id = $request->input('user_id');
                $startfrom = $request->input('startfrom', 1); // Default to 1 if not provided
                $totalrecords = $request->input('totalrecords', 10); // Default to 20 if not provided

                $complains = Complain::where('user_id', $user_id) ->skip(($startfrom - 1) * $totalrecords)
                    ->take($totalrecords)->orderBy('created_at', 'desc')
                    ->get();

                if ($complains->isEmpty()) {
                        return response()->json(['status' => 'false','msg' => 'No complains found for the given User ID.','data' => [],
                            ], 200);
                    } else {
                        return response()->json(['status' => 'true','msg' => 'All User Id base data','data' => $complains,
                        ], 200);
                }
            }


            public function Report_Store(Request $request)
            {

                $messages = array(
                    'user_id.required' => 'user id is required',
                );

                $validator = Validator::make($request->all(), [
                    'user_id' => 'required',
                    // Add more validation rules for other fields as needed
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'result' => false,
                        'message' => $validator->errors()
                    ]);
                }

                $params = [];

                if ($request->file('kata_slip_image')) {
                    $file = $request->file('kata_slip_image');
                    $filename = date('YmdHi') . '_' . $file->getClientOriginalName(); 
                    $file->move(public_path('public/Report'), $filename);
                    $params['kata_slip_image'] = $filename; 
                }

                if ($request->file('photo_click_lori_image')) {
                    $file = $request->file('photo_click_lori_image');
                    $filename = date('YmdHi') . '_' . $file->getClientOriginalName();
                    $file->move(public_path('public/Report'), $filename);
                    $params['photo_click_lori_image'] = $filename;
                }

                $report = Report::create([
                    'user_id' => $request->input('user_id'),
                    'location' => $request->input('location'),
                    'party_name' => $request->input('party_name'),
                    'mobile_no' => $request->input('mobile_no'),
                    'address' => $request->input('address'),
                    'item_name' => $request->input('item_name'),
                    'vahicle_no' => $request->input('vahicle_no'),
                    'gross_weight' => $request->input('gross_weight'),
                    'tare_weight' => $request->input('tare_weight'),
                    'net_weight' => $request->input('net_weight'),
                    'bag' => $request->input('bag'),
                    'moishcher' => $request->input('moishcher'),
                    'remarks' => $request->input('remarks'),
                    'kata_slip_image' => $params['kata_slip_image'] ?? null, 
                    'photo_click_lori_image' => $params['photo_click_lori_image'] ?? null,
                ]);

                if ($report) {
                    return response()->json(['status' => true, 'message' => 'Report created successfully'], 200);
                } else {
                    return response()->json(['status' => false, 'message' => 'Failed to create report'], 200);
                }
            }




            public function Reports_Show(Request $request)
            {
                $messages = array(
                    'user_id.required' => 'user id is required',
                );

                $validator = Validator::make($request->all(), [
                    'user_id' => 'required',
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'result' => false,
                        'message' => $validator->errors()
                    ]);
                }

                $user_id = $request->input('user_id');
                $startfrom = $request->input('startfrom', 1); 
                $totalrecords = $request->input('totalrecords', 10); 

                $query = Report::with('User', 'location')
                    ->where('user_id', $user_id)
                    ->orderBy('created_at', 'desc');

                if ($request->filled('location')) {
                    $query->where('location', $request->location);
                }

               
            

                if ($request->filled('date_from')) {
                    $query->whereDate('created_at', '=', $request->date_from);
                }

                $reports = $query->skip(($startfrom - 1) * $totalrecords)
                    ->take($totalrecords)
                    ->get();

                if ($reports->isEmpty()) {
                    return response()->json([
                        'status' => false,
                        'msg' => 'No reports found for the given User ID.',
                    ], 200);
                } else {
                    return response()->json([
                        'status' => true,
                        'data' => $reports,
                    ], 200);
                }
            }


            public function Reports_Show_Latest(Request $request)
            {
                $messages = [
                    'user_id.required' => 'User ID is required',
                ];

                $validator = Validator::make($request->all(), [
                    'user_id' => 'required',
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'status' => false,
                        'message' => $validator->errors()->first(),
                    ]);
                }

                $user_id = $request->input('user_id');

                $query = Report::with('User', 'location')
                    ->where('user_id', $user_id)
                    ->orderBy('created_at', 'desc')
                    ->take(10);

                if ($request->filled('location')) {
                    $query->where('location', $request->location);
                }

                if ($request->filled('date_from')) {
                    $query->whereDate('created_at', '=', $request->date_from);
                }

                $reports = $query->get();

                if ($reports->isEmpty()) {
                    return response()->json([
                        'status' => false,
                        'msg' => 'No reports found for the given User ID.',
                    ], 200);
                } else {
                    return response()->json([
                        'status' => true,
                        'data' => $reports,
                    ], 200);
                }
            }


            


            public function Reports_Details(Request $request)
            {

                $messages = array(
                    'id.required' => 'id is required',
                );

                $validator = Validator::make($request->all(), [
                    'id' => 'required',
                    // Add more validation rules for other fields as needed
                ], $messages);

                if ($validator->fails()) {
                    return response()->json([
                        'result' => false,
                        'message' => $validator->errors()
                    ]);
                }

                $id = $request->input('id');
                

                $reports = Report::with('User','location')->where('id', $id)->get();


                if ($reports->isEmpty()) {
                    return response()->json([
                        'status' => 'false',
                        'msg' => 'No reports found for the given ID.',
                    ], 200);
                } else {

                    return response()->json([
                        'status' => 'true',
                        'data' => $reports,
                    ], 200);
                }
            }



}




