<?php

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

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\Support\Facades\Storage;
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,
                'delivery_address' => $user->delivery_address,
                't_shirt_size' => $user->t_shirt_size,
                't_shirt_status' => $user->t_shirt_status,
                'cap_status' => $user->cap_status,
                'id_card_status' => $user->id_card_status,
                'handout_book_status' => $user->handout_book_status,
                't_shirt_updated_at' => $user->t_shirt_updated_at,
                'cap_updated_at' => $user->cap_updated_at,
                'id_card_updated_at' => $user->id_card_updated_at,
                'handout_book_updated_at' => $user->handout_book_updated_at,
                't_shirt_notes' => $user->t_shirt_notes,
                'cap_notes' => $user->cap_notes,
                'id_card_notes' => $user->id_card_notes,
                'handout_book_notes' => $user->handout_book_notes,
                'role' => $user->role,
                'profile_picture' => $profilePicture,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
            ]);
        } catch (\Exception $e) {
            Log::error('Student 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',
                'delivery_address' => 'nullable|string',
                't_shirt_size' => 'nullable|in:XS,S,M,L,XL,XXL,XXXL',
                'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:1024', // 1MB max
            ]);
            
            // 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 $this->error('The uploaded file is not valid.', ['profile_picture' => ['The uploaded file is not valid.']], 422);
                }
                
                // Check file size (additional validation)
                if ($file->getSize() > 1024 * 1024) { // 1MB
                    return $this->error('The image must not be larger than 1MB.', ['profile_picture' => ['The image must not be larger than 1MB.']], 422);
                }
                
                try {
                    // Get file contents and convert to base64
                    $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);
                    
                    // 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);
                    
                    $user->profile_picture = $encrypted;
                } catch (\Exception $e) {
                    Log::error('Profile picture encryption error: ' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine());
                    return $this->error('Failed to process the image. Please try a smaller file.', ['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'];
            }
            // Always update delivery_address if it's in the request
            if ($request->has('delivery_address')) {
                $deliveryAddress = $request->input('delivery_address');
                $user->delivery_address = (!empty($deliveryAddress) && trim($deliveryAddress) !== '') ? trim($deliveryAddress) : null;
            }
            // Always update t_shirt_size if it's in the request
            if ($request->has('t_shirt_size')) {
                $tShirtSize = $request->input('t_shirt_size');
                $user->t_shirt_size = (!empty($tShirtSize) && trim($tShirtSize) !== '') ? trim($tShirtSize) : null;
            }
            
            try {
                $user->save();
            } catch (\Illuminate\Database\QueryException $e) {
                // Check if it's a column not found error
                if (str_contains($e->getMessage(), "Unknown column") || 
                    str_contains($e->getMessage(), "doesn't exist") ||
                    str_contains($e->getMessage(), "SQLSTATE[42S22]")) {
                    Log::error('Delivery fields migration not run: ' . $e->getMessage() . ' | SQL: ' . $e->getSql());
                    return $this->error('Database migration required. The delivery fields have not been added to the database yet. Please run: php artisan migrate', ['error' => 'Missing database columns. Migration required.'], 500);
                }
                throw $e; // Re-throw if it's a different error
            }
            
            // 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,
                'delivery_address' => $user->delivery_address,
                't_shirt_size' => $user->t_shirt_size,
                't_shirt_status' => $user->t_shirt_status,
                'cap_status' => $user->cap_status,
                'id_card_status' => $user->id_card_status,
                'handout_book_status' => $user->handout_book_status,
                't_shirt_updated_at' => $user->t_shirt_updated_at,
                'cap_updated_at' => $user->cap_updated_at,
                'id_card_updated_at' => $user->id_card_updated_at,
                'handout_book_updated_at' => $user->handout_book_updated_at,
                't_shirt_notes' => $user->t_shirt_notes,
                'cap_notes' => $user->cap_notes,
                'id_card_notes' => $user->id_card_notes,
                'handout_book_notes' => $user->handout_book_notes,
                '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() . ' | User ID: ' . Auth::id());
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (QueryException $e) {
            Log::error('Profile database update error: ' . $e->getMessage() . ' | SQL: ' . $e->getSql() . ' | Bindings: ' . json_encode($e->getBindings()) . ' | User ID: ' . Auth::id());
            return $this->error('Database error occurred while updating profile.', ['error' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            Log::error('Profile update general error: ' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine() . ' | Trace: ' . $e->getTraceAsString());
            return $this->error('An error occurred while updating your profile. Please try again.', ['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',
            ]);
            
            // Verify current password
            if (!\Hash::check($validated['current_password'], $user->password)) {
                return $this->error('Current password is incorrect.', ['current_password' => ['Current password is incorrect.']], 422);
            }
            
            // Update password
            $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);
        }
    }
}

