<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use App\Mail\UserWarningMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;

class CustomerController extends Controller
{
    public function index()
    {
        $users = User::with('profile')->where('role', '!=', 2)->get();

        // Fetch latest subscription for each user
        $subscriptions = [];
        foreach ($users as $user) {
            $subscriptions[$user->id] = DB::table('user_subscription')
                ->where('user_id', $user->id)
                ->orderByDesc('id')
                ->first();
        }

        return view('backoffice.customer.index', compact('users', 'subscriptions'));
    }

    public function details($id)
    {
        // Fetch user and profile
        $user = DB::table('users')
            ->leftJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id')
            ->where('users.role', '!=', 2)
            ->where('users.id', $id)
            ->select('users.email', 'user_profiles.*') // include only fields you need
            ->first();

        if (empty($user)) {
            return redirect()->back();
        }

        // Get all subscriptions
        $subscriptions = DB::table('user_subscription')
            ->where('user_id', $id)
            ->orderByDesc('id')
            ->get();

        // Pass to view
        return view('backoffice.customer.details', compact('user', 'subscriptions'));
    }

    public function toggleStatus(User $user)
    {
        $user->is_active = !$user->is_active;
        $user->save();

        return response()->json(['status' => $user->is_active ? 'Active' : 'Inactive']);
    }

    public function sendWarning(Request $request, User $user)
    {
        if (!$user->email) {
            return response()->json(['status' => 'error', 'message' => 'User email not found.'], 404);
        }

        $realName = $user->profile->real_name ?? $user->name ?? 'User';

        // Send email
        Mail::to($user->email)->send(new UserWarningMail($realName));

        // ✅ Increment warning count
        $user->increment('warnings_count');

        return response()->json(['status' => 'success', 'message' => 'Warning email sent.']);
    }
}
