<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\QueryException;
use Illuminate\Validation\Rules\Password;

class ProfileController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }

    /**
     * Display the admin profile page.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $user = Auth::user();
        return view('admin.profile.index', compact('user'));
    }

    /**
     * Update the admin profile.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    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', // Reduced to 1MB
            ]);
            
            // Handle profile picture upload - encrypt and store in database
            if ($request->hasFile('profile_picture')) {
                $file = $request->file('profile_picture');
                
                // Validate file exists and is readable
                if (!$file->isValid()) {
                    return back()->withErrors(['profile_picture' => 'The uploaded file is not valid.'])->withInput();
                }
                
                // Check file size (additional validation)
                if ($file->getSize() > 1024 * 1024) { // 1MB
                    return back()->withErrors(['profile_picture' => 'The image must not be larger than 1MB.'])->withInput();
                }
                
                try {
                    // Get file contents and convert to base64
                    $imageData = file_get_contents($file->getRealPath());
                    
                    if ($imageData === false) {
                        return back()->withErrors(['profile_picture' => 'Failed to read the image file.'])->withInput();
                    }
                    
                    $base64 = base64_encode($imageData);
                    
                    // Get MIME type
                    $mimeType = $file->getMimeType();
                    
                    // Create data URI format: data:image/jpeg;base64,...
                    $dataUri = 'data:' . $mimeType . ';base64,' . $base64;
                    
                    // Encrypt the data URI
                    $encrypted = Crypt::encryptString($dataUri);
                    
                    $validated['profile_picture'] = $encrypted;
                } catch (\Exception $e) {
                    Log::error('Profile picture encryption error: ' . $e->getMessage());
                    return back()->withErrors(['profile_picture' => 'Failed to process the image. Please try a smaller file.'])->withInput();
                }
            }
            
            // Only update fields that are in the validated array
            $user->name = $validated['name'];
            $user->email = $validated['email'];
            
            if (isset($validated['phone'])) {
                $user->phone = $validated['phone'];
            }
            
            if (isset($validated['address'])) {
                $user->address = $validated['address'];
            }
            
            if (isset($validated['profile_picture'])) {
                $user->profile_picture = $validated['profile_picture'];
            }
            
            $user->save();
            
            return redirect()->route('admin.profile.index')
                ->with('success', 'Profile updated successfully!');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return back()->withErrors($e->errors())->withInput();
        } catch (\Illuminate\Database\QueryException $e) {
            Log::error('Profile update database error: ' . $e->getMessage() . ' | SQL: ' . $e->getSql());
            return back()->withErrors(['error' => 'Database error: ' . $e->getMessage()])->withInput();
        } catch (\Exception $e) {
            Log::error('Profile update error: ' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine() . ' | Trace: ' . $e->getTraceAsString());
            return back()->withErrors(['error' => 'Error: ' . $e->getMessage()])->withInput();
        }
    }

    /**
     * Update the admin password.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);
        
        $user = Auth::user();
        
        if (!Hash::check($request->current_password, $user->password)) {
            return back()->withErrors(['current_password' => 'The current password is incorrect.']);
        }
        
        $user->update([
            'password' => Hash::make($request->password),
        ]);
        
        return redirect()->route('admin.profile.index')
            ->with('success', 'Password updated successfully!');
    }
}

