<?php

namespace App\Http\Controllers\Reseller;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Models\ResellerCategory;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::where('status', 1)->get()->each(function($category){
            $reseller_category = ResellerCategory::where('category_id', $category->id)->where('reseller_id', session()->get('reseller')['id'])->first() ;
           if($reseller_category){
               $category->{'status'} =  $reseller_category->status;
           }else{
                $category->{'status'} =  $category->status;
           }
        });
        return response()->json([
            'categories' => $categories,
            'success' => true,
        ]);
    }


    public function status($id)
    {
        $reseller_id = session()->get('reseller')['id'];
        $category = Category::findOrFail($id);
        $reseller_category = ResellerCategory::where('reseller_id',$reseller_id)->where('category_id', $category->id)->first();
        if($reseller_category){
            if($reseller_category->status == 1){
                $reseller_category->status = 0;
                $reseller_category->save();
            }else{
                $reseller_category->status = 1;
                $reseller_category->save();
            }
        }else{
            $reseller_category = new ResellerCategory();
            $reseller_category->category_id = $category->id;
            $reseller_category->reseller_id = $reseller_id;
            if($category->status == 1){
                $reseller_category->status = 0;
                $reseller_category->save();
            }else{
                $reseller_category->status = 1;
                $reseller_category->save();
            }
        }
        return response()->json([
            'success' => true,
            'message' => 'Status Changed',
        ]);
    }
}
