<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Models\Categories;
use App\Models\CategoriesAudit;
use App\Repositories\ResponseRepository;

class CategoriesController extends Controller
{
    public function __construct(ResponseRepository $response)
    {
        $this->response = $response;
        $this->storeRules = [
            'categories_name' => 'required',
            'attachmenttype_id' => 'required',
            'active_status' => 'required',
        ];
    }

    // public function indexCategories() {
    //     return $this->response->jsonResponse(false," Categories Details Fetched Successfully", Categories::orderBy('categories_id', 'desc')->get(), 300);
    // }

    public function indexCategories()
    {
        $templates = Categories::orderBy('categories_id', 'desc')->get();

        // Retrieve categories for each template
        foreach ($templates as $template) {
            $template->categories = $template->attchmentlist();
        }

        $audits = CategoriesAudit::with('categories')->orderBy('created_at', 'desc')
            ->take(3)
            ->get();
        $data['data'] =  $templates;
        $data['recent_changes'] = $audits;
        return $this->response->jsonResponse(false, "Categories Details Fetched Successfully", $data, 300);
    }

    public function getActiveCategories()
    {
        return $this->response->jsonResponse(false, "Categories Detail Fetched Successfully",  Categories::where('active_status', 1)->orderBy('categories_id', 'desc')->get(), 300);
    }

    public function store(Request $request)
    {
        $validate = $this->response->validate($request->all(), $this->storeRules);
        if ($validate === true) {
            $data = $request->all();
            $data['attachmenttype_id'] = implode(',', $data['attachmenttype_id']); // Convert array to comma-separated string
            $result =  Categories::create($data);
            $this->logAudit('create', null, $result->toArray(), $result->categories_id);
            return $this->response->jsonResponse(false, $this->response->message('Categories', 'store'), $result, 301);
        } else {
            return $validate;
        }
    }








    public function show($id)
    {
        return $this->response->jsonResponse(false, $this->response->message('Categories', 'show'), $this->findCategoriesed($id), 302);
    }

    public function updateCategories(Request $request)
    {
        $validate = $this->response->validate($request->all(), [
            'categories_name' => 'required',
            'attachmenttype_id' => 'required',
            'active_status' => 'required'
        ]);
        if ($validate === true) {
            $data = $request->all();
            $data['attachmenttype_id'] = implode(',', $data['attachmenttype_id']); // Convert to comma-separated values
            $categories = $this->findCategories($request->categories_id);
            $oldData = $categories->toArray();
            $categories->update($data);
            $this->logAudit('update', $oldData, $request->all(), $categories->categories_id);
            return $this->response->jsonResponse(false, $this->response->message('Categories', 'update'), $categories, 303);
            // return $this->response->jsonResponse(false, $this->response->message('Categories', 'update'), $this->findCategories($request->categories_id)->update($request->all()), 303);
        } else {
            return $validate;
        }
    }







    public function destroy($id)
    {
        $size = $this->findCategories($id);
        if ($size) {
            return $this->response->jsonResponse(false, $this->response->message('Categories', 'destroy'), $size->delete(), 304);
        }
        return $this->response->jsonResponse(true, 'Categories Not Exists', [], 305);
    }

    public function findCategories($id)
    {
        return Categories::find($id);
    }
    public function findCategoriesed($id)
    {
        $Dish = Categories::find($id);
        if (!$Dish) {
            // Handle the case when the template is not found
            return null;
        }
        // Retrieve categories for the template
        $Dish->categories = $Dish->attchmentlist();
        return $Dish;
    }





    public function categoriesSwitch($id)
    {
        $size = $this->findCategories($id);
        if ($size) {
            $value = $size->active_status === 1 ? 0 : 1;
            $msg = $value === 0 ? 'Deactivated' : 'Activated';

            $oldStatus = $size->active_status;
            $newStatus = $oldStatus === 1 ? 0 : 1;
            $msg = $newStatus === 0 ? 'Deactivated' : 'Activated';
            $size->update(['active_status' => $newStatus]);
            $this->logAudit('status_change', ['active_status' => $oldStatus], ['active_status' => $newStatus], $id);
            return $this->response->jsonResponse(false, 'Categories ' . $msg . ' Successfully', $size, 306);
        }
        return $this->response->jsonResponse(true, 'Categories Not Exists', [], 307);
    }

    public function searchCategories($search)
    {
        if ($search === "null") {
            return $this->response->jsonResponse(false, $this->response->message('Categories', 'search'), [], 910);
        }
        return $this->response->jsonResponse(false, $this->response->message('Categories', 'search'), Categories::where('categories_name', 'LIKE', '%' . $search . '%')->get(), 911);
    }
    protected function logAudit($action, $oldData, $newData, $id)
    {
        CategoriesAudit::create([
            'categories_id' => $id,
            'action' => $action,
            'old_data' => $oldData ? json_encode($oldData) : null,
            'new_data' => json_encode($newData),
        ]);
    }
}
