<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Models\ClientDetails;
use App\Repositories\ResponseRepository;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class ClientDetailsController extends Controller
{
    public function __construct(ResponseRepository $response){
        $this->response = $response;
        $this->storeRules = [
            'first_name' => 'required',
            'last_name' => 'required',
            'client_id' => 'required',
            'title' => 'required',
            'mobile_no' => 'required',
            'user_id' => 'required',
            'password' => 'required',
            'end_date' => 'required',
        ];
        $this->storeRulestwo = [
            'client_image' => 'required',
        ];
    }

    public function indexClientDetails() {
        return $this->response->jsonResponse(false," ClientDetails Details Fetched Successfully", ClientDetails::with('clientslist')->orderBy('client_details_id', 'desc')->get() , 300);
    }

    public function getClientDetailsId($client_details_id) {
        return $this->response->jsonResponse(false, 'ClientDetails Details Fetched Successfully', ClientDetails::where('client_details_id', $client_details_id)->with('clientslist')->first(), 201);
    }

    
    // public function login(Request $request)
    // {
    //     $user_id = $request->input('user_id');
    //     $password = $request->input('password');

    //     // Check if the user exists in the database
    //     $user = ClientDetails::where('user_id', $user_id)->first();

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

    //     // Check if the password matches
    //     if ($password === $user->password) {
    //         return response()->json(['message' => 'Login successful']);
    //     } else {
    //         return response()->json(['message' => 'Invalid credentials'], 401);
    //     }
    // }

    public function login(Request $request)
{
    $user_id = $request->input('user_id');
    $password = $request->input('password');

    // Define an array of model classes
    $models = [
        \App\Models\ClientDetails::class,
        \App\Models\ContractorDetails::class,
        \App\Models\EmployeeDetails::class,
    ];

    foreach ($models as $modelClass) {
        // Check if the user exists in the current model
        $user = $modelClass::where('user_id', $user_id)->first();

        if ($user && $password === $user->password) {
            return response()->json(['message' => 'Login successful']);
        }
    }

    // If no matching user found
    return response()->json(['message' => 'Invalid credentials'], 401);
}


    // public function store(Request $request) {
    //     $validate = $this->response->validate($request->all(), $this->storeRules);
    //     if ($validate === true) {
    //         $data = $request->all();
    //         $password = $data['password'];
    
    //         // Create a new ClientDetails record
    //         $clientDetails = ClientDetails::create($data);
    
    //         // Create a new User record with the same password
    //         $user = User::create([
    //             'user_type_id' => $data['role_id'], // Assuming 'user_id' should be used as 'user_name'

    //             'user_name' => $data['user_id'], // Assuming 'user_id' should be used as 'user_name'
    //             'user_email' => $data['user_id'], // Assuming 'user_id' should be used as 'user_email'
    //             // 'user_name' => $data['user_type_id'],
    //             'password' => bcrypt($password), // Hash the password
    //             'active_status' => $data['active_status'],
    //         ]);
    
    //         return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'store'), $clientDetails, 301);
    //     } else {
    //         return $validate;
    //     }
    // }
    public function store(Request $request) {
        $validate = $this->response->validate($request->all(), $this->storeRules);
    
        if ($validate === true) {
            // Create a ClientDetails record
            $clientDetails = ClientDetails::create($request->all());
    
            // Create a User record with specific field mappings and set client_details_id
            $user = User::create([
                'user_name' => $request->input('user_id'),
                'user_email' => $request->input('user_id'),
                'role_id' => $request->input('role_id'),
                'password' => bcrypt($request->input('password')),
                'active_status' => $request->input('active_status') ?? 0,
                'client_details_id' => $clientDetails->client_details_id, // Set client_details_id from the created ClientDetails record
            ]);
    
            return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'store'), $clientDetails, 301);
        } else {
            return $validate;
        }
    }
    
    
    // public function store(Request $request) {
    //     $validate = $this->response->validate($request->all(), $this->storeRules);
    //     if ($validate === true) {
    //         $data = $request->all();
    //         $password = $data['password'];
    
    //         // Set the role_id to a fixed value of 8
    //         $data['role_id'] = 8;
    
    //         // Create a new ClientDetails record
    //         $clientDetails = ClientDetails::create($data);
    
    //         // Create a new User record with the same password
    //         $user = User::create([
    //             'user_name' => $data['user_id'],
    //             'user_type_id' =>  $data['role_id'],
    //             'user_email' => $data['user_id'],
    //             'password' => bcrypt($password),
    //             'active_status' => $data['active_status'],
    //         ]);
    
    //         return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'store'), $clientDetails, 301);
    //     } else {
    //         return $validate;
    //     }
    // }
    
    public function show($id) {
        return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'show'), $this->findClientDetails($id), 302);
    }

    public function imageuploaded(Request $request) {
        $getBanner = $this->findClientDetails($request['client_details_id']);
       if($request->hasFile('client_image')) {
           $file = $request->file('client_image');
           $name = $this->response->generateSlug($getBanner['first_name']);
           $uploadUrl = $this->response->cloudinaryImage($request->file('client_image'), 'Banner', $name);
           return $this->response->jsonResponse(false, $this->response->message('Client ', 'image'), $getBanner->update(['client_image' => $uploadUrl]), 108);
       } else {
           return $this->response->jsonResponse(true, 'Image is too high', [], 109);
       }
   }

   public function updateClientDetails(Request $request)
    {
        $validate = $this->response->validate($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'title' => 'required',
            'mobile_no' => 'required',
            'user_id' => 'required',
            'password' => 'required',
            'end_date' => 'required',
            'active_status' => 'required',
            'client_id' => 'required',
        ]);
        if($validate === true) {
            return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'update'), $this->findClientDetails($request->client_details_id)->update($request->all()), 303);
        } else {
            return $validate;
        }
    }

    public function destroy($id) {
        $size = $this->findClientDetails($id);
        if($size) {
            return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'destroy'), $size->delete(), 304);
        }
        return $this->response->jsonResponse(true, 'ClientDetails Not Exists', [], 305);
    }
        public function findClientDetails($id) {
            return ClientDetails::find($id);
        }

    public function clientdetailsSwitch($id) {
        $size = $this->findClientDetails($id);
        if($size) {
            $value = $size->active_status === 1 ? 0 : 1;
            $msg = $value === 0 ? 'Deactivated': 'Activated';
            return $this->response->jsonResponse(false, 'ClientDetails '.$msg.' Successfully', $size->update(['active_status' => $value]), 306);
        }
        return $this->response->jsonResponse(true, 'ClientDetails Not Exists', [], 307);
    }

    public function searchClientDetails($search){
        if($search === "null") {
            return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'search'), [], 910);
        }
        return $this->response->jsonResponse(false, $this->response->message('ClientDetails', 'search'), ClientDetails::where('first_name', 'LIKE', '%'.$search.'%')->get(), 911);
    }
}
