<?php
namespace App\Controllers;

use App\Models\adDashboardModel;

class adDashboard extends BaseController
{
    protected $dashboardModel;

    public function __construct()
    {
        helper(['url', 'form']);
        $this->dashboardModel = new adDashboardModel();
    }

    public function index()
    {
        $data = [
            'categoryCount' => $this->dashboardModel->getCategoryCount(),
            'productCount'  => $this->dashboardModel->getProductCount(),
            'pendingOrders' => $this->dashboardModel->getPendingOrdersCount(),
            'apartmentCount'=> $this->dashboardModel->getApartmentCount(),
            'products'      => $this->dashboardModel->getAllProductsWithVariants()
        ];

        return view('adDashboard_view', $data);
    }

    // Refill stock for a variant
    public function refillStock($id)
    {
        if ($this->request->isAJAX()) {
            $quantity     = (float)$this->request->getPost('quantity');
            $price        = (float)$this->request->getPost('price');
            $offer_price  = (float)$this->request->getPost('offer_price');

            $variant = $this->dashboardModel->getVariant($id);
            if (!$variant) {
                return $this->response->setJSON(['status' => 'error', 'message' => 'Variant not found']);
            }

            $newQty = $variant['quantity'] + $quantity;

            $this->dashboardModel->updateVariant($id, [
                'quantity'    => $newQty,
                'price'       => $price,
                'offer_price' => $offer_price
            ]);

            return $this->response->setJSON([
                'status'      => 'success',
                'quantity'    => $newQty,
                'price'       => $price,
                'offer_price' => $offer_price
            ]);
        }
    }
}
