<?php

namespace App\Http\Controllers;

use App\Helpers\TenantHelper;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\VendorUsers;

class CategoryController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
    }

    public function index()
    {
        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        $subcategories = $conn->table('vendor_subcategories')
            ->where('vendor_id', $vendor->id)
            ->orderBy('display_order')
            ->get();

        $categoriesJson = $subcategories->map(function ($c) {
            return [
                'id'      => $c->id,
                'name'    => $c->name,
                'order'   => $c->display_order ?? 0,
                'publish' => (bool) $c->publish,
            ];
        })->values();

        return view('category.index', [
            'subcategories'  => $subcategories,
            'categoriesJson' => $categoriesJson,
        ]);
    }

    public function edit($id)
    {
        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        $subcategory = $conn->table('vendor_subcategories')
            ->where('id', (int) $id)
            ->where('vendor_id', $vendor->id)
            ->first();

        if (!$subcategory) {
            abort(404, 'Category not found.');
        }

        return view('category.edit', ['subcategory' => $subcategory]);
    }

    public function create()
    {
        $conn      = $this->vendorConnection();
        $vendor    = $this->authVendorRow($conn);

        $nextOrder = $conn->table('vendor_subcategories')
            ->where('vendor_id', $vendor->id)
            ->count();

        return view('category.create', ['nextOrder' => $nextOrder]);
    }

    // ── API: store new category ───────────────────────────────────────────────

    public function apiStore(Request $request)
    {
        $data = $request->validate([
            'name'    => 'required|string|max:255',
            'publish' => 'required|boolean',
        ]);

        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        $nextOrder = $conn->table('vendor_subcategories')
            ->where('vendor_id', $vendor->id)
            ->count();

        $categoryId = $conn->table('vendor_categories')->value('id');

        $id = $conn->table('vendor_subcategories')->insertGetId([
            'name'          => $data['name'],
            'publish'       => $data['publish'],
            'vendor_id'     => $vendor->id,
            'display_order' => $nextOrder,
            'category_id'   => $categoryId,
        ]);

        return response()->json(['success' => true, 'id' => $id]);
    }

    // ── API: update category ─────────────────────────────────────────────────

    public function apiUpdate(Request $request, $id)
    {
        $data = $request->validate([
            'name'    => 'required|string|max:255',
            'publish' => 'required|boolean',
        ]);

        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        $updated = $conn->table('vendor_subcategories')
            ->where('id', (int) $id)
            ->where('vendor_id', $vendor->id)
            ->update([
                'name'    => $data['name'],
                'publish' => $data['publish'],
            ]);

        if (!$updated) {
            return response()->json(['success' => false, 'message' => 'Category not found'], 404);
        }

        return response()->json(['success' => true]);
    }

    // ── API: toggle publish ───────────────────────────────────────────────────

    public function apiTogglePublish(Request $request, $id)
    {
        $request->validate(['publish' => 'required|boolean']);

        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        $updated = $conn->table('vendor_subcategories')
            ->where('id', (int) $id)
            ->where('vendor_id', $vendor->id)
            ->update(['publish' => $request->boolean('publish')]);

        if (!$updated) {
            return response()->json(['success' => false, 'message' => 'Category not found'], 404);
        }

        return response()->json(['success' => true]);
    }

    // ── API: delete category ──────────────────────────────────────────────────

    public function apiDelete($id)
    {
        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        $deleted = $conn->table('vendor_subcategories')
            ->where('id', (int) $id)
            ->where('vendor_id', $vendor->id)
            ->delete();

        if (!$deleted) {
            return response()->json(['success' => false, 'message' => 'Category not found'], 404);
        }

        return response()->json(['success' => true]);
    }

    // ── API: update display order ─────────────────────────────────────────────

    public function apiUpdateOrder(Request $request)
    {
        $request->validate([
            'categoryIds'   => 'required|array',
            'categoryIds.*' => 'required|integer',
        ]);

        $conn   = $this->vendorConnection();
        $vendor = $this->authVendorRow($conn);

        foreach ($request->categoryIds as $index => $categoryId) {
            $conn->table('vendor_subcategories')
                ->where('id', (int) $categoryId)
                ->where('vendor_id', $vendor->id)
                ->update(['display_order' => $index]);
        }

        return response()->json(['success' => true]);
    }

    // ── Private helpers ───────────────────────────────────────────────────────

    private function vendorConnection()
    {
        $userId     = Auth::guard('admin')->id() ?? Auth::id();
        $vendorUser = VendorUsers::where('user_id', $userId)->firstOrFail();

        if (!$vendorUser->schema_name) {
            abort(500, 'Vendor schema not configured.');
        }

        TenantHelper::setSchema($vendorUser->schema_name);
        return DB::connection('pgsql_country');
    }

    private function authVendorRow($conn)
    {
        $userId = Auth::guard('admin')->id() ?? Auth::id();
        $vendor = $conn->table('vendors')->where('owner_id', $userId)->first();

        if (!$vendor) {
            abort(404, 'Vendor not found.');
        }

        return $vendor;
    }
}
