<?php

/**
 * Category Controller
 *
 * This file is used to register all actions for the Category Controller.
 *
 * @since 1.0.0
 */

namespace LinkFiliate\App\Controllers;

if (! defined('ABSPATH')) {
    exit;
}

use LinkFiliate\App\Models\Category as CategoryModel;

class Category
{

    /**
     * Get All Categories.
     */

    public function get_all()
    {
        $category = new CategoryModel();
        $result = $category->get_all();

        $categoryData = array();
        foreach ($result as $mktArr) {
            $mkt = json_decode(json_encode($mktArr)); // konversi array ke object

            // Build an array representing each row of data
            $rowData = array(
                'id' => $mkt->id,
                'name' => $mkt->name,
                'campaigns' => $mkt->total_campaigns,
                'created_at' => $mkt->created_at,
                'status' => $mkt->status,
            );

            // Add this row of data to the array of table data
            $categoryData[] = $rowData;
        }

        $response = new \WP_REST_Response([
            'status' => 'success',
            'data' => $categoryData
        ], 200);
        $response->set_headers([
            'Cache-Control' => 'no-cache, no-store, must-revalidate',
            'Expires' => '0',
            'Pragma' => 'no-cache',
        ]);
        return $response;
    }

    /**
     * Get Category by id.
     */

    public function get_by(\WP_REST_Request $request)
    {
        $id     = intval($request->get_param('id'));
        $category  = new CategoryModel();
        $resultArr = $category->find($id);

        // Check if result is not an array or is empty
        if (!$resultArr || !is_array($resultArr)) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Category not found'
            ], 404);
        }

        // Since we're looking for a single Category, we can directly format the result
        $result = json_decode(json_encode($resultArr));
        $categoryData = [
            'id' => $result->id,
            'name' => $result->name,
            'description' => $result->description,
            'image_url' => $result->image_url,
            'status' => $result->status,
            'text' => $result->predefined_text,
        ];

        return new \WP_REST_Response([
            'status' => 'success',
            'data' => $categoryData
        ], 200);
    }

    /**
     * Create Category Function.
     */
    public function create(\WP_REST_Request $request)
    {
        $data = $request->get_params();
        // Sanitize input
        $name        = sanitize_text_field($request->get_param('name'));
        $status      = sanitize_text_field($request->get_param('status'));
        $desc   = sanitize_text_field($request->get_param('desc'));
        $category = new CategoryModel();

        $inserted = $category->create([
            'name'        => $name,
            'status'      => $status,
            'description' => $desc,
        ]);

        if ($inserted === false) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => 'Failed to create Category'
            ], 500);
        }

        return new \WP_REST_Response([
            'status'  => 'success',
            'message' => 'Category created successfully',
            'data'    => [
                'id' => $inserted
            ]
        ], 200);
    }


    /**
     * Update Category Function.
     */
    public function update_by(\WP_REST_Request $request)
    {
        $id     = intval($request->get_param('id'));
        $name        = sanitize_text_field($request->get_param('name'));
        $status      = sanitize_text_field($request->get_param('status'));

        $image_url   = sanitize_text_field($request->get_param('image'));
        $desc   = sanitize_text_field($request->get_param('desc'));

        if (!$id) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => 'Invalid Category ID.'
            ], 400);
        }

        $category = new CategoryModel();

        $updated = $category->update($id, [
            'name'   => $name,
            'status' => $status,
            'description' => $desc,
            'updated_at' => current_time('mysql'),
        ]);

        if ($updated === false) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Failed to update Category'
            ], 500);
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'message' => 'Category updated successfully'
        ], 200);
    }

    /**
     * Delete Category Function.
     */
    public function delete_by(\WP_REST_Request $request)
    {
        $id     = intval($request->get_param('id'));
        $category  = new CategoryModel();
        $deleted = $category->delete($id);

        if ($deleted === false) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Failed to delete Category'
            ], 500);
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'message' => 'Category deleted successfully'
        ], 200);
    }
}
