<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\QueryException;

class ProfileController extends BaseController
{
    /**
     * Get user profile.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        try {
            $user = Auth::user();
            
            // Decrypt profile picture if exists
            $profilePicture = null;
            if ($user->profile_picture) {
                try {
                    $decrypted = Crypt::decryptString($user->profile_picture);
                    $profilePicture = $decrypted;
                } catch (\Exception $e) {
                    Log::warning('Profile picture decryption failed for user ' . $user->id);
                    $profilePicture = null;
                }
            }
            
            return $this->success([
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'address' => $user->address,
                'role' => $user->role,
                'profile_picture' => $profilePicture,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
            ]);
        } catch (\Exception $e) {
            Log::error('Admin Profile API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching profile.', null, 500);
        }
    }
    
    /**
     * Update user profile.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:500',
                'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:1024', // 1MB max
            ]);
            
            // Handle profile picture upload
            if ($request->hasFile('profile_picture')) {
                $file = $request->file('profile_picture');
                
                if (!$file->isValid()) {
                    return $this->error('The uploaded file is not valid.', ['profile_picture' => ['The uploaded file is not valid.']], 422);
                }
                
                if ($file->getSize() > 1024 * 1024) {
                    return $this->error('The image must not be larger than 1MB.', ['profile_picture' => ['The image must not be larger than 1MB.']], 422);
                }
                
                try {
                    $imageData = file_get_contents($file->getRealPath());
                    
                    if ($imageData === false) {
                        return $this->error('Failed to read the image file.', ['profile_picture' => ['Failed to read the image file.']], 422);
                    }
                    
                    $base64 = base64_encode($imageData);
                    $mimeType = $file->getMimeType();
                    $dataUri = 'data:' . $mimeType . ';base64,' . $base64;
                    $encrypted = Crypt::encryptString($dataUri);
                    
                    $user->profile_picture = $encrypted;
                } catch (\Exception $e) {
                    Log::error('Profile picture encryption error: ' . $e->getMessage());
                    return $this->error('Failed to process the image.', ['profile_picture' => ['Failed to process the image.']], 422);
                }
            } else if ($request->has('clear_profile_picture') && $request->clear_profile_picture == '1') {
                $user->profile_picture = null;
            }
            
            // Update other fields
            $user->name = $validated['name'];
            $user->email = $validated['email'];
            if (isset($validated['phone'])) {
                $user->phone = $validated['phone'];
            }
            if (isset($validated['address'])) {
                $user->address = $validated['address'];
            }
            
            $user->save();
            
            // Return updated profile
            $profilePicture = null;
            if ($user->profile_picture) {
                try {
                    $profilePicture = Crypt::decryptString($user->profile_picture);
                } catch (\Exception $e) {
                    $profilePicture = null;
                }
            }
            
            return $this->success([
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'address' => $user->address,
                'role' => $user->role,
                'profile_picture' => $profilePicture,
                'updated_at' => $user->updated_at,
            ], 'Profile updated successfully');
        } catch (\Illuminate\Validation\ValidationException $e) {
            Log::warning('Profile validation error: ' . $e->getMessage());
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (QueryException $e) {
            Log::error('Profile database update error: ' . $e->getMessage());
            return $this->error('Database error occurred.', ['error' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            Log::error('Profile update general error: ' . $e->getMessage());
            return $this->error('An error occurred while updating your profile.', ['error' => 'An unexpected error occurred.'], 500);
        }
    }
    
    /**
     * Change password.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Request $request)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'current_password' => 'required|string',
                'new_password' => 'required|string|min:8|confirmed',
            ]);
            
            if (!\Hash::check($validated['current_password'], $user->password)) {
                return $this->error('Current password is incorrect.', ['current_password' => ['Current password is incorrect.']], 422);
            }
            
            $user->password = \Hash::make($validated['new_password']);
            $user->save();
            
            return $this->success(null, 'Password changed successfully');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Exception $e) {
            Log::error('Password change API error: ' . $e->getMessage());
            return $this->error('An error occurred while changing password.', null, 500);
        }
    }
}

