<?php

namespace App\Http\Controllers;

use App\Helpers\ApiResponse;
use App\Mail\PasswordResetMail;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Carbon\Carbon;

class AuthController extends Controller
{
    // POST /api/login
    public function login(Request $request)
{
    $request->validate([
        'email'    => 'required|email',
        'password' => 'required'
    ]);

    $user = User::where('email', $request->email)->first();

    if (!$user || !Hash::check(
        $request->password, $user->password
    )) {
        return ApiResponse::error(
            'Invalid email or password', 401
        );
    }

    if (!$user->is_active) {
        return ApiResponse::error(
            'Your account is disabled. Contact admin.', 403
        );
    }

    // ── Create Sanctum token ──
    $token = $user->createToken('auth_token')->plainTextToken;

    // ── Also save plain token in users table
    //    ONLY for member role ──
    if ($user->role === 'member') {
        $user->auth_token = $token;
        $user->save();
    }

    return ApiResponse::success([
        'token' => $token,
        'role'  => $user->role,
        'user'  => [
            'id'    => (string) $user->id,
            'name'  => $user->name,
            'email' => $user->email,
            'phone' => $user->phone,
            'role'  => $user->role,
        ]
    ], 'Login successful');
}

    // POST /api/logout
    public function logout(Request $request)
{
    $user = $request->user();

    // ── Clear auth_token for member ──
    if ($user->role === 'member') {
        $user->auth_token = null;
        $user->save();
    }

    // ── Delete Sanctum token ──
    $user->currentAccessToken()->delete();

    return ApiResponse::success(
        null,
        'Logged out successfully'
    );
}

    // GET /api/me
    public function me(Request $request)
    {
        return ApiResponse::success(
            $request->user(),
            'Profile fetched successfully'
        );
    }

    // ─────────────────────────────────
// CHANGE PASSWORD (All roles)
// POST /api/change-password
// ─────────────────────────────────
    public function changePassword(Request $request)
{
    $request->validate([
        'current_password' => 'required|string',
        'new_password'     => 'required|string|min:8',
        'confirm_password' => 'required|same:new_password',
    ]);

    $user = auth()->user();

    if (!Hash::check(
        $request->current_password, $user->password
    )) {
        return ApiResponse::error(
            'Current password is incorrect.', 400
        );
    }

    if (Hash::check(
        $request->new_password, $user->password
    )) {
        return ApiResponse::error(
            'New password must be different from current password.', 400
        );
    }

    $user->password = Hash::make($request->new_password);
    $user->save();

    // ── Revoke all Sanctum tokens ──
    $user->tokens()->delete();

    // ── Clear auth_token for member ──
    if ($user->role === 'member') {
        $user->auth_token = null;
        $user->save();
    }

    // ── Create new Sanctum token ──
    $newToken = $user->createToken('auth_token')->plainTextToken;

    // ── Save new auth_token for member ──
    if ($user->role === 'member') {
        $user->auth_token = $newToken;
        $user->save();
    }

    return ApiResponse::success(
        ['token' => $newToken],
        'Password changed successfully!'
    );
}

// ─────────────────────────────────
    // FORGOT PASSWORD (API — JSON)
    // POST /api/forgot-password
    // ─────────────────────────────────
    public function forgotPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        // Only for members — not admin/unit_admin
        $user = User::where('email', $request->email)
                    ->where('role', 'member')
                    ->first();

        // Always return success — don't reveal if email exists
        if (!$user) {
            return ApiResponse::success(
                null,
                'If that email exists, a reset link has been sent.'
            );
        }

        // Delete old token
        DB::table('password_reset_tokens')
            ->where('email', $request->email)->delete();

        // Generate token
        $token = Str::random(64);

        DB::table('password_reset_tokens')->insert([
            'email'      => $request->email,
            'token'      => Hash::make($token),
            'created_at' => Carbon::now(),
        ]);

        // For mobile app — deep link URL
        // The app opens this link and shows the reset password screen
        $resetUrl = config('app.url') . '/reset-password?token=' . $token . '&email=' . urlencode($request->email);

        // Reuse existing PasswordResetMail
        Mail::to($user->email)->send(
            new PasswordResetMail($resetUrl, $user->name)
        );

        return ApiResponse::success(
            null,
            'If that email exists, a reset link has been sent.'
        );
    }

    // ─────────────────────────────────
    // RESET PASSWORD (API — JSON)
    // POST /api/reset-password
    // ─────────────────────────────────
    public function resetPassword(Request $request)
    {
        $request->validate([
            'email'                 => 'required|email',
            'token'                 => 'required|string',
            'password'              => 'required|min:8|confirmed',
            'password_confirmation' => 'required',
        ]);

        // Find token record
        $record = DB::table('password_reset_tokens')
                    ->where('email', $request->email)
                    ->first();

        if (!$record) {
            return ApiResponse::error('Invalid or expired reset link.', 400);
        }

        // Check 60 min expiry
        if (Carbon::parse($record->created_at)->addMinutes(60)->isPast()) {
            DB::table('password_reset_tokens')
                ->where('email', $request->email)->delete();
            return ApiResponse::error('Reset link has expired. Please request a new one.', 400);
        }

        // Verify token
        if (!Hash::check($request->token, $record->token)) {
            return ApiResponse::error('Invalid reset token.', 400);
        }

        // Find member user only
        $user = User::where('email', $request->email)
                    ->where('role', 'member')
                    ->first();

        if (!$user) {
            return ApiResponse::error('User not found.', 404);
        }

        // Update password
        $user->password = Hash::make($request->password);
        $user->save();

        // Delete used token
        DB::table('password_reset_tokens')
            ->where('email', $request->email)->delete();

        // Revoke all tokens — force re-login
        $user->tokens()->delete();

        return ApiResponse::success(
            null,
            'Password reset successfully. Please login with your new password.'
        );
    }


}
