<?php

namespace App\Controllers;

use App\Core\Controller;
use Exception;

/**
 * Dashboard landing page and stats API.
 */
class DashboardController extends Controller
{
    /**
     * Render dashboard with key metrics and recent activity.
     */
    public function index()
    {
        $this->requireAuth();

        // Get models
        $inventoryModel = $this->model('InventoryModel');
        $productModel = $this->model('ProductModel');
        $transactionModel = $this->model('TransactionModel');
        $logModel = $this->model('LogModel');
        $notificationModel = $this->model('NotificationModel');

        // Fetch low stock items once to avoid multiple queries
        $lowStockItems = $inventoryModel->getLowStockItemsDetailed();

        $this->notifications = $notificationModel->getUnreadNotifications($_SESSION['user_id']);

        // Get dashboard statistics
        $data = [
            'total_products' => $productModel->count(),
            'low_stock_items' => $lowStockItems,
            'recent_transactions' => $transactionModel->getTransactionHistory(['limit' => 10]),
            'recent_logs' => $logModel->getLogs(5),
            'stock_by_location' => $this->getStockByLocation($inventoryModel)
        ];

        $this->view('dashboard/index', $data);
    }

    /**
     * Provide dashboard statistics as JSON.
     */
    public function getStats()
    {
        $this->requireAuth();
        header('Content-Type: application/json');

        $inventoryModel = $this->model('InventoryModel');
        $productModel = $this->model('ProductModel');
        $transactionModel = $this->model('TransactionModel');

        $data = [
            'total_products' => $productModel->count(),
            'total_inventory' => $inventoryModel->getTotalStockQuantity(), // Assuming this method exists
            'low_stock_items' => count($inventoryModel->getLowStockItemsDetailed()),

            'todays_transactions' => $transactionModel->getTodaysTransactionCount() // Assuming this method exists
        ];

        echo json_encode($data);
        exit;
    }



    /**
     * Summarize stock levels per location for dashboard charts.
     *
     * @param mixed $inventoryModel Inventory model instance.
     * @return array Location stock summary.
     */
    private function getStockByLocation($inventoryModel)
    {
        $locations = $this->db->query("SELECT * FROM locations")->fetchAll();
        $stockData = [];

        foreach ($locations as $location) {
            $stock = $inventoryModel->getStockByLocation($location['id']);
            $totalQuantity = array_sum(array_column($stock, 'quantity'));
            $stockData[] = [
                'location' => $location['name'],
                'total_items' => count($stock),
                'total_quantity' => $totalQuantity
            ];
        }

        return $stockData;
    }
}
