<?php

namespace App\Http\Controllers\student;

use App\Http\Controllers\Controller;
use App\Models\FileUploader;
use App\Models\User;
use App\Models\Instructors;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;


class MyProfileController extends Controller
{
    public function index()
    {
        $user = User::find(auth()->user()->id);
        // Check if the role is 'instructor'
        if ($user->role === 'instructor') {
            // Retrieve the instructor details associated with the user
            $instructor = Instructors::where('user_id', $user->id)->first();

            // Check if the instructor exists to avoid errors when accessing properties
            if ($instructor) {
                $user->nidn = $instructor->nidn;
                $user->id_sdm = $instructor->id_sdm;
                $user->id_sms = $instructor->id_sms;
                $user->id_pt = $instructor->id_pt;
            }
        }
        $page_data['user_details'] = $user;
        $view_path                 = 'frontend.' . get_frontend_settings('theme') . '.student.my_profile.index';

        return view($view_path, $page_data);
    }

    public function update(Request $request, $user_id)
    {
        $rules = [
            'name'  => 'required',
            'email' => 'required|email|unique:users,email,' . $user_id,
        ];
        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data['name']      = $request->name;
        $data['phone']     = $request->phone;
        $data['website']   = $request->website;
        $data['facebook']  = $request->facebook;
        $data['twitter']   = $request->twitter;
        $data['linkedin']  = $request->linkedin;
        $data['skills']    = $request->skills;
        $data['biography'] = $request->biography;

        User::where('id', $user_id)->update($data);
        Session::flash('success', get_phrase('Profile updated successfully.'));
        return redirect()->back();
    }

    public function update_profile_picture(Request $request)
    {
        $request->validate([
            'photo' => 'required|image|mimes:jpeg,png,jpg,webp,tiff|max:3072',
        ]);

        // process file
        $file      = $request->photo;
        $file_name = Str::random(20) . '.' . $file->extension();
        $path      = 'uploads/users/' . auth()->user()->role . '/' . $file_name;
        FileUploader::upload($file, $path, null, null, 300);

        User::where('id', auth()->user()->id)->update(['photo' => $path]);
        Session::flash('success', get_phrase('Profile picture updated.'));
        return redirect()->back();
    }

    public function changePassword(Request $request)
    {
        $user = auth()->user();
        
        $rules = [];
        
        // Define validation rules
        if (is_null($user->password)) {
            $rules = [
                'new_password' => 'required|min:8',
                'confirm_password' => 'required|same:new_password',
            ];
        } else {
            $rules = [
                'current_password' => 'required',
                'new_password' => 'required|min:8',
                'confirm_password' => 'required|same:new_password',
            ];
        }
        
        $validator = Validator::make($request->all(), $rules);
        
        // Custom messages with get_phrase
        $validator->setCustomMessages([
            'current_password.required' => get_phrase('Current password is required'),
            'new_password.required' => get_phrase('New password is required'),
            'new_password.min' => get_phrase('New password must be at least 8 characters'),
            'confirm_password.required' => get_phrase('Confirm password is required'),
            'confirm_password.same' => get_phrase('Confirm password does not match'),
        ]);
        
        // Custom attribute names (optional, makes error messages nicer)
        $validator->setAttributeNames([
            'current_password' => get_phrase('Current password'),
            'new_password' => get_phrase('New password'),
            'confirm_password' => get_phrase('Confirm password'),
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        
        // Check current password if exists
        if (!is_null($user->password)) {
            // Using Hash::check instead of Auth::attempt for better performance
            if (!Hash::check($request->current_password, $user->password)) {
                Session::flash('error', get_phrase('Current password is incorrect'));
                return redirect()->back();
            }
        }
        
        // Update password
        $user->update(['password' => Hash::make($request->new_password)]);
        
        // Success message
        $successMessage = is_null($user->password) 
            ? get_phrase('Password set successfully') 
            : get_phrase('Password changed successfully');
        
        Session::flash('success', $successMessage);
        return redirect()->back();
    }
    
}
