<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\CreateAssetRequest;
use Illuminate\Support\Facades\Log;

use App\Services\AdminService;
use App\Models\Customer;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use App\Models\Asset;
use App\Models\UserAssetLink;
use Exception;

class AssetadmintController extends Controller
{
    private $adminService;

    public function __construct(AdminService $adminService)
    {
        $this->adminService = $adminService;
    }

    // public function storeAssest(CreateAssetRequest $request)
    // {
    //     try {
    //         $additionalInfo = $request->has('additional_info') && is_string($request->additional_info)
    //             ? json_decode($request->additional_info, true)
    //             : $request->additional_info;

    //         $assetData = [
    //             'entity_type' => $request->entity_type,
    //             'createdTime' => $request->created_time ?? now()->timestamp,
    //             'tenantId' => $request->tenant_id ?? Str::uuid()->toString(),
    //             'customerId' => $request->customer_xid,
    //             'name' => $request->name,
    //             'type' => $request->type,
    //             'label' => $request->label,
    //             'assetProfileId' => $request->asset_profile_id ?? Str::uuid()->toString(),
    //             'externalId' => $request->external_id ?? Str::uuid()->toString(),
    //             'version' => $request->version ?? '1.0',
    //             'additionalInfo' => $additionalInfo ?? ['description' => 'Default asset description'],
    //         ];

    //         $response = $this->adminService->createAsset($assetData);

    //         if (!$response) {
    //             throw new Exception('Failed to create asset via admin service');
    //         }

    //         $asset = new Asset();
    //         $asset->id = $response['id']['id'] ?? Str::uuid()->toString();
    //         $asset->entity_type = $response['entityType'] ?? $assetData['entity_type'];
    //         $asset->created_time = $response['createdTime'] ?? $assetData['createdTime'];
    //         $asset->tenant_id = $assetData['tenantId'];
    //         $asset->customer_xid = $assetData['customerId'];
    //         $asset->name = $response['name'] ?? $assetData['name'];
    //         $asset->type = $response['type'] ?? $assetData['type'];
    //         $asset->label = $response['label'] ?? $assetData['label'];
    //         $asset->asset_profile_id = $assetData['assetProfileId'];
    //         $asset->external_id = $assetData['externalId'];
    //         $asset->version = $response['version'] ?? $assetData['version'];
    //         $asset->additional_info = json_encode($response['additionalInfo'] ?? $assetData['additionalInfo']);

    //         $asset->save();

    //         return response()->json([
    //             'message' => 'Asset created successfully!',
    //             'data' => $asset,
    //             'api_response' => $response
    //         ], 200);
    //     } catch (Exception $e) {
    //         Log::error('Error in creating asset: ' . $e->getMessage());
    //         return response()->json(['error' => $e->getMessage()], 500);
    //     }
    // }

    public function storeAssest(Request $request)
    {
        try {
            $assetData = [
                'entity_type' => 'ASSET',
                'createdTime' => now()->timestamp,
                'tenantId' => $request->tenant_id ?? Str::uuid()->toString(),
                'customerId' => $request->customer_xid,
                'name' => $request->name,
                'type' => $request->type ?? 'Default Type',
                'label' => $request->label ?? '',
                'assetProfileId' => $request->asset_profile_id ?? Str::uuid()->toString(),
                'externalId' => $request->external_id ?? Str::uuid()->toString(),
                'version' => $request->version ?? '1.0',
                'additionalInfo' => $request->additionalInfo
            ];

            // Check if ID exists in request for update
            if ($request->has('id')) {
                $asset = Asset::find($request->id);
                if (!$asset) {
                    throw new \Exception('Asset not found');
                }

                $assetNameExists = Asset::where('name', $request->name)->where('id','!=',$request->id)->first();
                if ($assetNameExists) {
                    return jsonResponseWithErrorMessage('Asset name already exists', 400);
                }

                // Update local database record
                $asset->name = $assetData['name'];
                $asset->type = $assetData['type'];
                $asset->customer_xid = $assetData['customerId'];
                $asset->label = $assetData['label'];
                $asset->version = $assetData['version'];
                $asset->additional_info = json_encode( $assetData['additionalInfo']);
                $asset->save();

                $message = 'Asset updated successfully!';
            } else {

                $assetNameExists = Asset::where('name', $request->name)->first();
                if ($assetNameExists) {
                    return jsonResponseWithErrorMessage('Asset name already exists', 400);
                }

                // Create new asset via admin service
                $response = $this->adminService->createAsset($assetData);
                if (!$response) {
                    throw new \Exception('Failed to create asset via admin service');
                }

                // Create new local database record
                $asset = new Asset();
                $asset->id = $response['id']['id'] ?? Str::uuid()->toString();
                $asset->entity_type = $assetData['entity_type'];
                $asset->created_time = $assetData['createdTime'];
                $asset->tenant_id = $assetData['tenantId'];
                $asset->customer_xid = $assetData['customerId'];
                $asset->name = $response['name'] ?? $assetData['name'];
                $asset->type = $response['type'] ?? $assetData['type'];
                $asset->label = $response['label'] ?? $assetData['label'];
                $asset->asset_profile_id = $assetData['assetProfileId'];
                $asset->external_id = $assetData['externalId'];
                $asset->version = $response['version'] ?? $assetData['version'];
                $asset->additional_info = json_encode($response['additionalInfo'] ?? $assetData['additionalInfo']);
                $asset->save();

                $message = 'Asset created successfully!';
            }

            // Fetch customer name
            $customerName = \App\Models\Customer::where('id', $assetData['customerId'])->value('name');

            return response()->json([
                'status_code' => 200,
                'message' => $message,
                'data' => $asset,
                'customer_name' => $customerName,
                // 'api_response' => $response
            ], 200);

        } catch (\Exception $e) {
            Log::error('Error in asset operation: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }





    // public function listAssest()
    // {
    //     try {
    //         $assets = Asset::with('customer')->get()->map(function ($asset) {
    //             $assetData = $asset->toArray();
    //             unset($assetData['customer']);
    //             $assetData['customer_name'] = $asset->customer?->name;
    //             return $assetData;
    //         });

    //         return jsonResponseWithSuccessMessage('Assets fetched successfully', [
    //             'assests' => $assets
    //         ]);
    //     } catch (Exception $e) {

    //         Log::error("An error occurred: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }

    // public function listAssest()
    // {
    //     try {
    //         $assets = Asset::with([
    //             'customer:id,name',
    //             'userAssetLinks.user:id,first_name' // eager load first_name only
    //         ])->get()->map(function ($asset) {
    //             $assetData = $asset->toArray();

    //             unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects

    //             $assetData['customer_name'] = $asset->customer?->name;

    //             // Collect user first names from user_asset_links
    //             $userFirstNames = $asset->userAssetLinks->map(function ($userAssetLink) {
    //                 return optional($userAssetLink->user)->first_name;
    //             })->filter()->values(); // remove nulls and reset keys

    //             $assetData['assign_to_user'] = $userFirstNames;

    //             return $assetData;
    //         });

    //         return jsonResponseWithSuccessMessage('Assets fetched successfully', [
    //             'assets' => $assets
    //         ]);
    //     } catch (Exception $e) {
    //         Log::error("An error occurred: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }

    // public function listAssest()
    // {
    //     try {
    //         $assets = Asset::with([
    //             'customer:id,name',
    //             'userAssetLinks.user:id,first_name,last_name' // eager load first_name and last_name
    //         ])->get()->map(function ($asset) {
    //             $assetData = $asset->toArray();

    //             unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects

    //             $assetData['customer_name'] = $asset->customer?->name;

    //             // Collect user id and full name (first_name + last_name) from user_asset_links
    //             $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) {
    //                 $user = $userAssetLink->user;
    //                 if ($user) {
    //                     return [
    //                         'user_id' => $user->id,
    //                         'full_name' => trim($user->first_name . ' ' . $user->last_name),
    //                     ];
    //                 }
    //                 return null;
    //             })->filter()->values(); // remove nulls and reset keys

    //             $assetData['assign_to_users'] = $assignToUsers;

    //             return $assetData;
    //         });

    //         return jsonResponseWithSuccessMessage('Assets fetched successfully', [
    //             'assets' => $assets
    //         ]);
    //     } catch (Exception $e) {
    //         Log::error("An error occurred: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }

    public function listAssest()
    {
        try {
            $assets = Asset::with([
                'customer:id,name',
                'userAssetLinks' => function ($query) {
                    $query->where('active', 1) // Only fetch active user asset links
                        ->with(['user:id,first_name,last_name']); // Eager load user info
                }
            ])
            ->orderBy('created_at', 'desc')
            ->get()->map(function ($asset) {
                $assetData = $asset->toArray();

                unset($assetData['customer'], $assetData['user_asset_links']); // remove full objects

                $assetData['customer_name'] = $asset->customer?->name;

                // Collect user id and full name (first_name + last_name) from active user_asset_links
                $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) {
                    $user = $userAssetLink->user;
                    if ($user) {
                        return [
                            'user_id' => $user->id,
                            'full_name' => trim($user->first_name . ' ' . $user->last_name),
                        ];
                    }
                    return null;
                })->filter()->values(); // remove nulls and reset keys

                // $assetData['assign_to_users'] = !empty($assignToUsers) ? implode(', ', $assignToUsers) : '';
                $assetData['assign_to_users'] = $assignToUsers;

                return $assetData;
            });

            return jsonResponseWithSuccessMessage('Assets fetched successfully', [
                'assets' => $assets
            ]);
        } catch (Exception $e) {
            Log::error("An error occurred: " . $e->getMessage());
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }








    public function deleteAsset(Request $request)
    {
        $assetId = $request->input('assetId');  // Fetching ID from request body

        if (!$assetId) {
            return jsonResponseWithErrorMessage('Asset ID is required', 400);
        }

        try {
            $response = $this->adminService->deleteAsset(['assetId' => $assetId]);
            Log::info("Asset delete API response", ['response' => $response]);

            if (!is_array($response)) {
                Log::error("Unexpected API response format", ['response' => $response]);
                return jsonResponseWithErrorMessage('Unexpected API response format', 500);
            }

            if (isset($response['status']) && $response['status'] === 400) {
                Log::error("API failed to delete asset", ['message' => $response['message']]);
                return jsonResponseWithErrorMessage($response['message'], 400, $response);
            }

            if (empty($response)) {
                Log::error("API response is empty while deleting asset");
                return jsonResponseWithErrorMessage('Failed to delete asset', 400);
            }

            // Delete from local database
            $asset = Asset::find($assetId);
            if ($asset) {
                $asset->delete();
            } else {
                Log::warning("Asset not found in DB", ['assetId' => $assetId]);
            }

            return jsonResponseWithSuccessMessage('Asset deleted successfully', ['api_response' => $response]);
        } catch (\Exception $e) {
            Log::error("Exception while deleting asset", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            return jsonResponseWithErrorMessage('An error occurred while deleting the asset', 500);
        }
    }


    // public function assignAssetToUser(Request $request)
    // {

    //     try {
    //         $request->validate([
    //             'user_id' => 'required|exists:users,id',
    //             'asset_id' => 'required|uuid'
    //         ]);

    //         $userId = $request->user_id;
    //         $assetId = $request->asset_id;

    //         $userAssetLink = UserAssetLink::where('user_id', $userId)
    //             ->where('asset_id', $assetId)
    //             ->first();

    //         if (!$userAssetLink) {
    //             $userAssetLink = new UserAssetLink();
    //             $userAssetLink->user_id = $userId;
    //             $userAssetLink->asset_id = $assetId;
    //             $userAssetLink->active = 1;
    //             $userAssetLink->save();

    //             Log::info("Asset successfully assigned to user.", ['userId' => $userId, 'assetId' => $assetId]);

    //             return response()->json([
    //                 'success' => true,
    //                 'message' => 'Asset assigned to user successfully.',
    //                 'data' => $userAssetLink
    //             ], 200);
    //         }

    //         if ($userAssetLink->active == 1) {
    //             $userAssetLink->active = 0;
    //             $userAssetLink->save();
    //             return response()->json([
    //                 'success' => true,
    //                 'message' => 'Asset unassigned from user.',
    //                 'data' => $userAssetLink
    //             ], 200);
    //         }

    //         $userAssetLink->active = 1;
    //         $userAssetLink->save();
    //         return response()->json([
    //             'success' => true,
    //             'message' => 'Asset reassigned to user successfully.',
    //             'data' => $userAssetLink
    //         ], 200);
    //     } catch (Exception $e) {
    //         Log::error("Error assigning asset: " . $e->getMessage());
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to assign or unassign asset to user',
    //             'error' => $e->getMessage()
    //         ], 500);
    //     }
    // }

    // public function assignAssetToUser(Request $request)
    // {
    //     try {
    //         $request->validate([
    //             'user_id' => 'required|exists:users,id',
    //             'asset_id' => 'required|uuid',
    //             'active'   => 'required|boolean'
    //         ]);

    //         $userId = $request->user_id;
    //         $assetId = $request->asset_id;
    //         $activeStatus = $request->active;

    //         $userAssetLink = UserAssetLink::where('user_id', $userId)
    //             ->where('asset_id', $assetId)
    //             ->first();

    //         if (!$userAssetLink) {
    //             $userAssetLink = new UserAssetLink();
    //             $userAssetLink->user_id = $userId;
    //             $userAssetLink->asset_id = $assetId;
    //         }

    //         $userAssetLink->active = $activeStatus;
    //         $userAssetLink->save();

    //         $message = $activeStatus
    //             ? 'Asset assigned to user successfully.'
    //             : 'Asset unassigned from user.';

    //         Log::info($message, ['userId' => $userId, 'assetId' => $assetId]);

    //         return response()->json([
    //             'success' => true,
    //             'message' => $message,
    //             'data' => $userAssetLink
    //         ], 200);
    //     } catch (Exception $e) {
    //         Log::error("Error assigning/unassigning asset: " . $e->getMessage());
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Failed to assign or unassign asset to user',
    //             'error' => $e->getMessage()
    //         ], 500);
    //     }
    // }
    public function assignAssetToUser(Request $request)
    {
        try {
            $request->validate([
                'user_id' => 'required|exists:users,id',
                'asset_id' => 'required|uuid',
                'active'   => 'required|boolean'
            ]);

            $userId = $request->user_id;
            $assetId = $request->asset_id;
            $activeStatus = $request->active;

            // Now either update existing record or create a new one for this user and asset
            if($userId){
                foreach($userId as $user){
                    $userAssetLink = UserAssetLink::firstOrNew([
                        'user_id' => $user,
                        'asset_id' => $assetId
                    ]);

                    $userAssetLink->active = $activeStatus;
                    $userAssetLink->save();
                }
            }

            $message = $activeStatus
                ? 'Asset assigned to user(s) successfully'
                : 'Asset unassigned from user(s)';

            Log::info($message, ['userId' => $userId, 'assetId' => $assetId]);

            return response()->json([
                'success' => true,
                'message' => $message,
            ], 200);
        } catch (Exception $e) {
            Log::error("Error assigning/unassigning asset: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to assign or unassign asset to user',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    public function customerList()
    {
        try {

            $customers = Customer::all();
            return jsonResponseWithSuccessMessage('Customers fetched successfully', [
                'customers' => $customers
            ]);
        } catch (Exception $e) {
            Log::error("An error occurred: " . $e->getMessage());
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }


    // public function assestlistCustomer($customerId)
    // {
    //     try {
    //         $assets = Asset::with('customer:id,name')
    //             ->where('customer_xid', $customerId)
    //             ->get()
    //             ->map(function ($asset) {
    //                 return collect($asset)
    //                     ->except('customer') // remove the full customer object
    //                     ->merge([
    //                         'customer_name' => optional($asset->customer)->name,
    //                     ]);
    //             });

    //         if ($assets->isEmpty()) {
    //             return response()->json(['message' => 'No assets found for this customer ID'], 200);
    //         }

    //         return jsonResponseWithSuccessMessage('Assets fetched successfully', [
    //             'assets' => $assets
    //         ]);
    //     } catch (Exception $e) {
    //         Log::error("An error occurred in asset listing: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }

    // public function assestlistCustomer($customerId)
    // {
    //     try {
    //         $assets = Asset::with([
    //             'customer:id,name',
    //             'userAssetLinks.user:id,name' // eager load user through userAssetLink
    //         ])
    //             ->where('customer_xid', $customerId)
    //             ->get()
    //             ->map(function ($asset) {
    //                 // Get user names linked to the asset
    //                 $userNames = $asset->userAssetLinks->map(function ($userAssetLink) {
    //                     return optional($userAssetLink->user)->name;
    //                 })->filter()->values(); // filter nulls and reset keys

    //                 return collect($asset)
    //                     ->except('customer', 'userAssetLinks') // remove full objects
    //                     ->merge([
    //                         'customer_name' => optional($asset->customer)->name,
    //                         'assign_to_user' => $userNames, // attach user names
    //                     ]);
    //             });

    //         if ($assets->isEmpty()) {
    //             return response()->json(['message' => 'No assets found for this customer ID'], 200);
    //         }

    //         return jsonResponseWithSuccessMessage('Assets fetched successfully', [
    //             'assets' => $assets
    //         ]);
    //     } catch (Exception $e) {
    //         Log::error("An error occurred in asset listing: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }

    // public function assestlistCustomer($customerId)
    // {
    //     try {
    //         $assets = Asset::with([
    //             'customer:id,name',
    //             'userAssetLinks.user:id,first_name,last_name' // eager load first_name and last_name
    //         ])
    //             ->where('customer_xid', $customerId)
    //             ->get()
    //             ->map(function ($asset) {
    //                 // Get user details (id and full name) linked to the asset
    //                 $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) {
    //                     $user = $userAssetLink->user;
    //                     if ($user) {
    //                         return [
    //                             'user_id' => $user->id,
    //                             'full_name' => trim($user->first_name . ' ' . $user->last_name),
    //                         ];
    //                     }
    //                     return null;
    //                 })->filter()->values(); // filter nulls and reset keys

    //                 return collect($asset)
    //                     ->except('customer', 'userAssetLinks') // remove full objects
    //                     ->merge([
    //                         'customer_name' => optional($asset->customer)->name,
    //                         'assign_to_users' => $assignToUsers, // attach user_id and full_name
    //                     ]);
    //             });

    //         if ($assets->isEmpty()) {
    //             return response()->json(['message' => 'No assets found for this customer ID'], 200);
    //         }

    //         return jsonResponseWithSuccessMessage('Assets fetched successfully', [
    //             'assets' => $assets
    //         ]);
    //     } catch (Exception $e) {
    //         Log::error("An error occurred in asset listing: " . $e->getMessage());
    //         return jsonResponseWithErrorMessage($e->getMessage(), 500);
    //     }
    // }


    public function assestlistCustomer($customerId)
    {
        try {
            $assets = Asset::with([
                'customer:id,name',
                'userAssetLinks' => function ($query) {
                    $query->where('active', 1) // Only active links
                        ->with('user:id,first_name,last_name'); // Eager load user
                }
            ])
                ->where('customer_xid', $customerId)
                ->get()
                ->map(function ($asset) {
                    // Since only active userAssetLinks are fetched, take the first one (only one user per asset)
                    $assignToUsers = $asset->userAssetLinks->map(function ($userAssetLink) {
                        $user = $userAssetLink->user;
                        if ($user) {
                            return [
                                'user_id' => $user->id,
                                'full_name' => trim($user->first_name . ' ' . $user->last_name),
                            ];
                        }
                    });

                    return collect($asset)
                        ->except('customer', 'user_asset_links') // remove full objects
                        ->merge([
                            'customer_name' => optional($asset->customer)->name,
                            'assign_to_users' => $assignToUsers, // attach user_id and full_name
                        ]);
                });

            if ($assets->isEmpty()) {
                return response()->json(['message' => 'No assets found for this customer ID'], 200);
            }

            return jsonResponseWithSuccessMessage('Assets fetched successfully', [
                'assets' => $assets
            ]);
        } catch (Exception $e) {
            Log::error("An error occurred in asset listing: " . $e->getMessage());
            return jsonResponseWithErrorMessage($e->getMessage(), 500);
        }
    }
}
