<?php

namespace App\Http\Controllers\Admin;
use App\Models\IamPrincipal;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;

class ManageProfileController extends Controller
{
    /**
    * Created By : sayali parab
    * Created at : 29 May 2024
    * Use : To get and update admin profile.
    */
    
    public function index()
    {
        $get_user = Auth::guard('admin')->user();
        $user = IamPrincipal::find($get_user->id);
        return view('Admin.pages.manage_profile.manage_profile', compact('user'));
    }
    public function update_profile(Request $request)
    {
        $request->validate([
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'phone_number' => 'required|string',
            'email_address' => 'required|email',
        ]);

        try {
            DB::beginTransaction();

            // Get the authenticated user
            $user_detail = Auth::guard('admin')->user();
            $user = IamPrincipal::find($user_detail->id);

            // Check if the provided email address already exists for another user
            $existingUser = IamPrincipal::where('email_address', $request->input('email_address'))
                ->where('id', '!=', $user->id)
                ->first();

            if ($existingUser) {
                return response()->json(['error' => 'Email address already exists.'], 400);
            }

            // Update profile information
            $user->first_name = $request->input('first_name');
            $user->last_name = $request->input('last_name');
            $user->phone_number = $request->input('phone_number');
            $user->email_address = $request->input('email_address');

            // Check if a new profile photo is provided
            if ($request->hasFile('profile_photo')) {
                // Get the file
                $image = $request->file('profile_photo');

                $imageFilename = saveSingleImageWithoutCrop($image, 'admin_images', $user->profile_photo);

                $user->profile_photo = $imageFilename;

            }

            // Save changes to the user
            $user->save();

            DB::commit();

            return response()->json(['success' => true, 'status' => 200]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Profile update failed: " . $e->getMessage());
            return response()->json(['message' => 'Failed to update profile'], 500);
        }
    }
}
