<?php

namespace App\Http\Controllers\Api\Employee;

use App\Http\Controllers\Controller;
use App\Models\Locker;
use App\Models\LockerRegistration;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * Handle employee login request
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    // public function login(Request $request)
    // {
    //     $validator = Validator::make($request->all(), [
    //         'locker_number' => 'required|exists:lockers,locker_number',
    //         'password' => 'required|string|min:6',
    //     ]);

    //     if ($validator->fails()) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Validation failed',
    //             'errors' => $validator->errors()
    //         ], 422);
    //     }

    //     $locker = Locker::where('locker_number', $request->locker_number)->first();

    //     if (!$locker) {
    //         throw ValidationException::withMessages([
    //             'locker_number' => ['Locker not found.'],
    //         ]);
    //     }

    //     // Get the locker registration to find the password
    //     $lockerRegistration = LockerRegistration::where('locker_id', $locker->id)
    //         ->where('status', 'active')
    //         ->first();

    //     if (!$lockerRegistration) {
    //         throw ValidationException::withMessages([
    //             'locker_number' => ['Locker is not registered or inactive.'],
    //         ]);
    //     }

    //     // Check password against the stored locker password
    //     if ($request->password !== $lockerRegistration->locker_password) {
    //         throw ValidationException::withMessages([
    //             'locker_number' => ['The provided credentials are incorrect.'],
    //         ]);
    //     }

    //     // Get the client information
    //     $client = $lockerRegistration->client;
        
    //     if (!$client) {
    //         throw ValidationException::withMessages([
    //             'locker_number' => ['Client not found for this locker.'],
    //         ]);
    //     }

    //     // Check if client is active
    //     if ($client->status_id && $client->status->name !== 'active') {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Your account is not active. Please contact administrator.'
    //         ], 403);
    //     }

    //     // Create new token for the client
    //     $token = $client->createToken('customer-app-token', ['customer'])->plainTextToken;

    //     // Update last login
    //     $client->update(['last_login_at' => now()]);

    //     return response()->json([
    //         'success' => true,
    //         'message' => 'Login successful',
    //         'data' => [
    //             'user' => [
    //                 'id' => $client->id,
    //                 'name' => $client->name,
    //                 'email' => $client->email,
    //                 'phone' => $client->phone,
    //                 'last_login_at' => $client->last_login_at,
    //                 'locker_info' => [
    //                     'locker_id' => $locker->id,
    //                     'locker_number' => $locker->locker_number,
    //                     'locker_size' => $locker->locker_size,
    //                     'locker_type' => $locker->locker_type,
    //                 ]
    //             ],
    //             'token' => $token,
    //             'token_type' => 'Bearer'
    //         ]
    //     ]);
    // }
    
    // public function login(Request $request)
    // {
    //     $validator = Validator::make($request->all(), [
    //         // 'locker_number' => 'required|exists:lockers,locker_number',
    //         'locker_number' => 'required|string|exists:lockers,locker_number,status,Occupied',
    //         'password' => 'required|string|min:6',
    //     ]);

    //     if ($validator->fails()) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Validation failed',
    //             'errors' => $validator->errors()
    //         ], 422);
    //     }

    //     $locker = Locker::where('locker_number', $request->locker_number)
    //         ->where('status', 'Occupied')
    //         ->first();

    //     if (!$locker) {
    //         return response()->view('errors.locker-error', [
    //             'message' => 'Locker not found or not occupied.'
    //         ], 404);
    //     }

    //     // Get the locker registration to find the password
    //     $lockerRegistration = LockerRegistration::where('locker_id', $locker->id)
    //         ->where('status', 'active')
    //         ->first();

    //     if (!$lockerRegistration) {
    //         return response()->view('errors.locker-error', [
    //             'message' => 'Locker is not registered or inactive.'
    //         ], 404);
    //     }

    //     // Check password against the stored locker password
    //     if ($request->password !== $lockerRegistration->locker_password) {
    //         // throw ValidationException::withMessages([
    //         //     'locker_number' => ['The provided credentials are incorrect.'],
    //         // ]);
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Invalid credentials'
    //         ], 401);
    //     }

    //     // Get the client information
    //     $client = $lockerRegistration->client;

    //     if (!$client) {
    //         return response()->view('errors.locker-error', [
    //             'message' => 'Client not found for this locker.'
    //         ], 404);
    //     }

    //     // Check if client is active
    //     if ($client->status_id && $client->status->name !== 'active') {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Your account is not active. Please contact administrator.'
    //         ], 403);
    //     }

    //     // Create new token for the client
    //     $token = $client->createToken('customer-app-token', ['customer'])->plainTextToken;

    //     // Update last login
    //     $client->update(['last_login_at' => now()]);

    //     return response()->json([
    //         'success' => true,
    //         'message' => 'Login successful',
    //         'data' => [
    //             'user' => [
    //                 'id' => $client->id,
    //                 'name' => $client->name,
    //                 'email' => $client->email,
    //                 'phone' => $client->phone,
    //                 'last_login_at' => $client->last_login_at,
    //                 'locker_info' => [
    //                     'locker_id' => $locker->id,
    //                     'locker_number' => $locker->locker_number,
    //                     'locker_size' => $locker->locker_size,
    //                     'locker_type' => $locker->locker_type,
    //                 ]
    //             ],
    //             'token' => $token,
    //             'token_type' => 'Bearer'
    //         ]
    //     ]);
    // }
    
    public function login(Request $request)
    {

        
        $validator = Validator::make($request->all(), [
            'locker_number' => 'required|string|exists:locker_registration_items,locker_number',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        // Check locker_number in locker_registration_items table
        $lockerRegistrationItem = DB::table('locker_registration_items')
            ->where('locker_number', $request->locker_number)
            ->first();

        if (!$lockerRegistrationItem) {
            return response()->json([
                'success' => false,
                'message' => 'Locker number not found.'
            ], 404);
        }

        // Get locker registration details using registration_id
        $lockerRegistration = DB::table('locker_registrations')
            ->where('id', $lockerRegistrationItem->registration_id)
            ->first();

        if (!$lockerRegistration) {
            return response()->json([
                'success' => false,
                'message' => 'Locker registration not found.'
            ], 404);
        }

        // Check password against the stored locker password
        if ($request->password !== $lockerRegistration->locker_password) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid credentials'
            ], 401);
        }

        // Get client information using client_id
        $client = DB::table('clients')
            ->where('id', $lockerRegistration->client_id)
            ->first();

        if (!$client) {
            return response()->json([
                'success' => false,
                'message' => 'Client not found for this locker.'
            ], 404);
        }

        // Create new token for the client (using Client model if available)
        $clientModel = \App\Models\Client::find($client->id);
        if ($clientModel) {
            $token = $clientModel->createToken('customer-app-token', ['customer'])->plainTextToken;
            
            // Update last login
            $clientModel->update(['last_login_at' => now()]);
            $lastLoginAt = $clientModel->last_login_at;
        } else {
            // Fallback if model not available
            $token = 'temp-token-' . uniqid();
            $lastLoginAt = now();
            DB::table('clients')
                ->where('id', $client->id)
                ->update(['last_login_at' => $lastLoginAt]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Login successful',
            'data' => [
                'user' => [
                    'id' => $client->id,
                    'name' => $client->name,
                    'email' => $client->email,
                    'phone' => $client->phone,
                    'last_login_at' => $lastLoginAt,
                    'locker_info' => [
                        'locker_id' => $lockerRegistrationItem->id,
                        'locker_number' => $lockerRegistrationItem->locker_number,
                        'registration_id' => $lockerRegistration->id
                    ]
                ],
                'token' => $token,
                'token_type' => 'Bearer'
            ]
        ]);
    }
    


    /**
     * Handle employee logout request
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        // Revoke the current user's token
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logout successful'
        ]);
    }
}

