<?php

namespace App\Http\Controllers\Api\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\School;
use Illuminate\Support\Facades\Hash;
use Exception;

class ProfileController extends Controller
{
    // School Profile Edit
    public function editProfile(Request $request)
    {
        try {
             $user = School::find(auth()->user()->id);

             // Validation rules
             $validation = Validator::make($request->all(), [
                 'school_name' => 'required|min:2|max:100',
                 'username' => 'required|string|max:255|unique:schools,username,' . $user->id . '|regex:/^[a-zA-Z0-9_]+$/',
                 'email' => 'required|email|unique:schools,email,' . $user->id,
                 'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
                 'phone' => 'nullable|numeric',
             ]);

             // Check validation
             if ($validation->fails()) {
                 return response()->json([
                     'validation_errors' => $validation->messages(),
                     'response_status' => 400,
                 ], 200);
             }

             // Update profile information
            $user->school_name = $request->school_name;
             $user->username = $request->username;
             $user->email = $request->email;
             $user->phone = $request->phone;

             // Create Image Process
             $filename = '';

             if ($request->hasFile('image')) {
                 $file = $request->file('image');
                 $extension = $file->getClientOriginalExtension();
                 $filename = time() . '.' . $extension;
                 $path = public_path('uploads/schools/');
                 // Delete the old image if it exists
                 if ($user->image && file_exists($path . $user->image)) {
                     unlink($path . $user->image);
                 }

                 // Move the new image to the path
                 $file->move($path, $filename);

                 // Update the user image filename
                 $user->image = $filename;
             }

             // Save user
             $user->save();
             $data = [
                'school_name' => $user->school_name,
                'username' => $user->username,
                'email' => $user->email,
                'phone' => $user->phone,
                'image' => $user->image ? $user->image : null,
            ];

             return response()->json([
                 'response_message' => ['success' => ['Profile Updated Successfully!']],
                 'response_status' => 200,
                 'data' => ['user' => $data],
             ], 200);

        } catch (Exception $exception) {
            return response()->json([
                'validation_errors' => $exception->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    // Change Password
    public function changePassword(Request $request)
    {
        try{
            $validation = Validator::make($request->all(), [
                'old_password' => 'required|exists:schools,password',
                'new_password' => 'required|min:8',
                'confirm_password' => 'required|same:new_password'
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            $user = School::find(auth()->user()->id);
            if(Hash::check($request->old_password, $user->password)){
                $user->password = Hash::make($request->new_password);
                $user->save();
                return response([
                    'response_message' => ['success' => ['Password Updated Successfully!']],
                    'response_status' => 200
                ],200);
            }else{
                return response([
                    'validation_errors' => ['incorrect' => ['Incorrect Old Password!']],
                    'response_status' => 400
                ],200);
            }
        } catch (Exception $exception) {
            return response()->json([
                'validation_errors' => $exception->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
}
