<?php

namespace App\Http\Controllers;

use App\Mail\UserOtpMail;
use App\Models\Admin;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class AdminAuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:admins',
            'password' => 'required|string|confirmed|min:6',
            'role_id' => 'required|exists:roles,id'
        ]);

        $admin = Admin::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role_id' => $request->role_id
        ]);

        return response()->json(['admin' => $admin], 201);
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string|min:6'
        ]);

        $admin = Admin::where('email', $request->email)->first();

        if (!$admin || !Hash::check($request->password, $admin->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

        $token = $admin->createToken('admin_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'user' => $admin->only('name', 'email'),
        ]);
    }

    // Send OTP for forgot password
    public function sendOtp(Request $request)
    {
        $request->validate(['email' => 'required|email|exists:admins,email']);

        $otp = rand(100000, 999999); // 6-digit OTP

        DB::table('admin_password_resets')->updateOrInsert(
            ['email' => $request->email],
            [
                'otp' => $otp,
                'created_at' => Carbon::now()
            ]
        );

        // Optionally send OTP via email
        Mail::to($request->email)->send(new UserOtpMail($otp));

        return response()->json(['message' => 'OTP sent', 'otp' => $otp]); // remove 'otp' in production
    }

    // Verify OTP
    public function verifyOtp(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:admins,email',
            'otp' => 'required|string'
        ]);

        $record = DB::table('admin_password_resets')
            ->where('email', $request->email)
            ->where('otp', $request->otp)
            ->first();

        if (!$record) {
            return response()->json(['message' => 'Invalid OTP'], 400);
        }

        // Optional: check expiry (e.g., 10 minutes)
        if (Carbon::parse($record->created_at)->addMinutes(10)->isPast()) {
            return response()->json(['message' => 'OTP expired'], 400);
        }

        return response()->json(['message' => 'OTP verified']);
    }

    // Reset password
    public function resetPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:admins,email',
            'otp' => 'required|string',
            'password' => 'required|min:6|confirmed'
        ]);

        $record = DB::table('admin_password_resets')
            ->where('email', $request->email)
            ->where('otp', $request->otp)
            ->first();

        if (!$record) {
            return response()->json(['message' => 'Invalid OTP'], 400);
        }

        // Optional: check expiry
        if (Carbon::parse($record->created_at)->addMinutes(10)->isPast()) {
            return response()->json(['message' => 'OTP expired'], 400);
        }

        $admin = Admin::where('email', $request->email)->first();
        $admin->password = Hash::make($request->password);
        $admin->save();

        // Delete OTP after use
        DB::table('admin_password_resets')->where('email', $request->email)->delete();

        return response()->json(['message' => 'Password reset successfully']);
    }

    // Get admin profile
    public function profile(Request $request)
    {
        $admin = $request->user()->load('role'); // authenticated admin

        // Append full URL for profile image
        if ($admin->profile_image) {
            $admin->profile_image = asset('storage/' . $admin->profile_image);
        }

        return response()->json(['data' => $admin]);
    }


    // Update admin profile
    public function updateProfile(Request $request)
    {
        $admin = $request->user();

        $request->validate([
            'name' => 'sometimes|required|string|max:255',
            // 'email' => 'sometimes|required|email|unique:admins,email,' . $admin->id,
            'password' => 'sometimes|required|string|min:6|confirmed',
            'profile_image' => 'sometimes|image|max:20480',
            'phone' => 'sometimes|nullable|string|max:20',
            'address' => 'sometimes|nullable|string|max:255',
            'dob' => 'sometimes|nullable|date',
            'gender' => 'sometimes|nullable|in:male,female,other',
        ]);

        if ($request->has('name')) {
            $admin->name = $request->name;
        }
        if ($request->has('address')) {
            $admin->address = $request->address;
        }
        if ($request->has('phone')) {
            $admin->phone = $request->phone;
        }
        if ($request->has('dob')) {
            $admin->dob = $request->dob;
        }
        if ($request->has('gender')) {
            $admin->gender = $request->gender;
        }

        // if ($request->has('email')) {
        //     $admin->email = $request->email;
        // }

        if ($request->has('password')) {
            $admin->password = Hash::make($request->password);
        }

        if ($request->hasFile('profile_image')) {
            // Delete old image if exists
            if ($admin->profile_image) {
                Storage::disk('public')->delete($admin->profile_image);
            }

            $path = $request->file('profile_image')->store('admin/profile_images', 'public');
            $admin->profile_image = $path;
        }

        $admin->save();

        return response()->json(['message' => 'Profile updated', 'data' => $admin]);
    }

    public function logout(Request $request)
    {
        $request->user()->tokens()->delete();
        return response()->json(['message' => 'Logged out']);
    }
}
