<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use DB;
use Auth;

class MyprofileController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    // public function __construct()
    // {
    //     $this->middleware('permission:view users')->only(['index', 'show']);
    //     $this->middleware('permission:create users')->only(['create', 'store']);
    //     $this->middleware('permission:edit users')->only(['edit', 'update']);
    //     $this->middleware('permission:delete users')->only(['destroy']);
    // }


    public function index()
    {
        $myprofile = Auth::guard('admin')->user(); 
        return view('admin.myprofile.edit', compact('myprofile'));
    }

   

    public function update_profile(Request $request)
    {
        $id = base64_decode($request->id);

        $rules = [
            'name'   => 'required',
            'email'  => 'required|email',
            'image'  => 'nullable|image|mimes:jpeg,png,jpg,gif',

            
        ];

        $messages = [
            'name.required'    => 'Name is required.',
            'email.required'  => 'Email is required.',
            'image.image'     => 'The uploaded file must be an image.',
            'image.mimes'     => 'Only jpeg, png, jpg, and gif formats are allowed.',

           
        ];

        $validation = Validator::make($request->all(), $rules, $messages);

        if ($validation->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ]);
        }

        // DB::beginTransaction();

        try {
            $profile = Admin::findOrFail($id);

            $profile->name  = $request->name;
            $profile->email = $request->email;
            $profile->mobile_number = $request->mobile_number;

            if ($request->hasFile('image') && $request->file('image')->isValid()) {
                $file = $request->file('image');
                $filename = 'img_' . time() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('storage/user'), $filename);

                // Remove old image
                if ($profile->image && file_exists(public_path('storage/user/' . $profile->image))) {
                    unlink(public_path('storage/user/' . $profile->image));
                }

                $profile->image = $filename;
            }
           
            $profile->save();

            // DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Myprofile updated successfully.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'errors' => ['server' => [$e->getMessage()]]
            ]);
        }
    }

   
    public function changePassword(Request $request)
{
        $rules = [
        'old_password' => 'required',
        'password' => 'required|min:6|confirmed',
    ];

    $messages = [
        'old_password.required' => 'Old password is required.',
        'password.required' => 'New password is required.',
        'password.min' => 'Password must be at least 6 characters.',
        'password.confirmed' => 'Confirm password does not match the new password.',
    ];


   $validation = Validator::make($request->all(), $rules, $messages);

    if ($validation->fails()) {
        $errors = $validation->errors()->getMessages();

        // Move 'password.confirmed' error to 'password_confirmation' only
        if (isset($errors['password'])) {
            foreach ($errors['password'] as $key => $msg) {
                if (str_contains($msg, 'Confirm password does not match')) {
                    // Add to confirmation field
                    $errors['password_confirmation'][] = $msg;

                    // Remove from password field
                    unset($errors['password'][$key]);
                }
            }

            // Clean up empty 'password' key
            if (empty($errors['password'])) {
                unset($errors['password']);
            }
        }

        return response()->json([
            'success' => false,
            'errors' => $errors
        ]);
    }
    // Auth::user()->password;
    $admin = Auth::guard('admin')->user(); 
    if (!Hash::check($request->old_password, $admin->password)) {
        return response()->json([
            'success' => false,
            'errors' => ['old_password' => ['Old password is incorrect.']]
        ]);
    }

    try {
        $admin->password = Hash::make($request->password);
        $admin->save();

        return response()->json([
            'success' => true,
            'message' => 'Password updated successfully.'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'errors' => ['server' => [$e->getMessage()]]
        ]);
    }
}



 

  
   
   
}
