<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Carbon\Carbon;
use DataTables;
use Illuminate\Support\Facades\Validator;

class LicenseController extends Controller
{
    public function __construct()
    {
        // অ্যাডমিন গার্ড এবং মিডলওয়্যার নিশ্চিত করা হয়েছে
        $this->middleware('auth:admin');
    }

    // =========================================================
    // ১. লাইসেন্স লিস্ট (Datatables)
    // =========================================================
    public function index(Request $request)
    {
        if ($request->ajax()) {
            // ইউজারের সাথে রিলেশনশিপ লোড
            $datas = License::with('user')->orderBy('id', 'desc')->get();

            return DataTables::of($datas)
                ->addIndexColumn()
                ->addColumn('client_name', function(License $data) {
                    return '<div class="client-info"><b>'.($data->user ? $data->user->name : 'N/A').'</b><small>'.($data->user ? $data->user->email : '').'</small></div>';
                })
                ->addColumn('domain_info', function(License $data) {
                    return '<div>
                                <span class="font-weight-bold text-dark d-block">' . $data->domain_name . '</span>
                                <a href="http://' . $data->domain_name . '" target="_blank" class="btn-visit-link">
                                    <i class="fas fa-external-link-alt"></i> Visit Site
                                </a>
                            </div>';
                })
                ->addColumn('expiry', function(License $data) {
                    $date = Carbon::parse($data->expiry_date);
                    return '<span class="text-dark">' . $date->format('d M, Y') . '</span><br><small class="text-muted">(' . $date->diffForHumans() . ')</small>';
                })
                ->editColumn('status', function(License $data) {
                    $class = $data->status == 1 ? 'badge-active' : 'badge-expired';
                    $text = $data->status == 1 ? 'Active' : 'Expired';
                    return '<span class="' . $class . '">' . $text . '</span>';
                })
                ->addColumn('action', function(License $data) {
                    return '<div class="action-btn-group">
                                <button type="button" data-href="' . route('admin.license.edit', $data->id) . '" class="btn-modern btn-edit edit-btn" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button type="button" data-href="' . route('admin.license.delete', $data->id) . '" class="btn-modern btn-delete delete-btn" title="Delete">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>';
                })
                ->rawColumns(['client_name', 'domain_info', 'expiry', 'status', 'action'])
                ->make(true);
        }

        $users = User::orderBy('name', 'asc')->get();
        return view('admin.license.index', compact('users'));
    }

    // =========================================================
    // ২. নতুন লাইসেন্স তৈরি (Store)
    // =========================================================
    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required',
            'domain_name' => 'required|unique:licenses,domain_name',
            'validity' => 'required|integer|in:1,2,3'
        ]);

        $license = new License();
        $license->user_id = $request->user_id;
        $license->domain_name = $request->domain_name;
        $license->license_key = 'LIC-' . strtoupper(Str::random(4)) . '-' . strtoupper(Str::random(4)) . '-' . strtoupper(Str::random(4));
        $license->expiry_date = Carbon::now()->addYears($request->validity);
        $license->status = 1;
        $license->save();

        return back()->with('success', 'New License Key Generated Successfully!');
    }

    // =========================================================
    // ৩. এডিট ডাটা (Ajax Response with User Relation)
    // =========================================================
    public function edit($id)
    {
        // এখানে with('user') ব্যবহার করা হয়েছে যাতে পপআপে ইউজারের নাম দেখা যায়
        $data = License::with('user')->findOrFail($id);
        return response()->json($data);
    }

    // =========================================================
    // ৪. লাইসেন্স আপডেট
    // =========================================================
    public function update(Request $request, $id)
    {
        $rules = [
            'user_id'     => 'required',
            'domain_name' => 'required|unique:licenses,domain_name,' . $id,
            'status'      => 'required'
        ];

        $validator = Validator::make($request->all(), $rules);
        
        if ($validator->fails()) {
            return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
        }

        $license = License::findOrFail($id);
        $license->user_id     = $request->user_id; 
        $license->domain_name = $request->domain_name;
        $license->status      = $request->status;
        $license->save();

        return response()->json(['status' => 'success', 'message' => 'License updated successfully']);
    }

    // =========================================================
    // ৫. লাইসেন্স ডিলিট
    // =========================================================
    public function delete($id)
    {
        $license = License::findOrFail($id);
        $license->delete();
        
        return response()->json(['status' => 'success', 'message' => 'License deleted successfully']);
    }
}