<?php
declare(strict_types=1);

namespace App\Modules\Procurement\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class DeliveryTrackingController extends Controller
{
    public function overdueDeliveries(Request $request): Response
    {
        $this->authorize('procurement.report');
        $db = App::getInstance()->db();

        $supplierId = (int) $request->get('supplier_id', 0);
        $where = "poi.expected_delivery_date < CURDATE() AND poi.delivery_status IN ('pending','partial')";
        $params = [];

        if ($supplierId) {
            $where .= ' AND po.supplier_id = ?';
            $params[] = $supplierId;
        }

        $overdue = $db->select(
            "SELECT poi.*, po.po_number, po.supplier_id, s.name_ar as supplier_name,
                    i.name_ar as item_name, i.sku,
                    DATEDIFF(CURDATE(), poi.expected_delivery_date) as days_overdue
             FROM purchase_order_items poi
             JOIN purchase_orders po ON po.id = poi.purchase_order_id
             JOIN suppliers s ON s.id = po.supplier_id
             JOIN inventory_items i ON i.id = poi.item_id
             WHERE {$where}
             ORDER BY days_overdue DESC",
            $params
        );

        $suppliers = $db->select("SELECT id, name_ar FROM suppliers WHERE is_archived = 0 ORDER BY name_ar");

        return $this->view('Procurement.Views.reports.overdue_deliveries', [
            'overdue' => $overdue,
            'suppliers' => $suppliers,
            'supplier_id' => $supplierId,
        ]);
    }

    public function poBalance(Request $request): Response
    {
        $this->authorize('procurement.report');
        $db = App::getInstance()->db();

        $supplierId = (int) $request->get('supplier_id', 0);
        $where = "po.status IN ('approved','partial')";
        $params = [];

        if ($supplierId) {
            $where .= ' AND po.supplier_id = ?';
            $params[] = $supplierId;
        }

        $orders = $db->select(
            "SELECT po.id, po.po_number, po.created_at as order_date, po.total_amount, po.status,
                    s.name_ar as supplier_name,
                    SUM(poi.quantity) as total_qty_ordered,
                    SUM(poi.qty_received) as total_qty_received,
                    SUM(poi.quantity - poi.qty_received) as total_qty_remaining,
                    CASE WHEN SUM(poi.quantity) > 0
                         THEN ROUND((SUM(poi.qty_received) / SUM(poi.quantity)) * 100, 1)
                         ELSE 0 END as delivery_percentage
             FROM purchase_orders po
             JOIN suppliers s ON s.id = po.supplier_id
             JOIN purchase_order_items poi ON poi.purchase_order_id = po.id
             WHERE {$where}
             GROUP BY po.id
             ORDER BY delivery_percentage ASC",
            $params
        );

        $suppliers = $db->select("SELECT id, name_ar FROM suppliers WHERE is_archived = 0 ORDER BY name_ar");

        return $this->view('Procurement.Views.reports.po_balance', [
            'orders' => $orders,
            'suppliers' => $suppliers,
            'supplier_id' => $supplierId,
        ]);
    }

    public function priceDeviation(Request $request): Response
    {
        $this->authorize('procurement.report');
        $db = App::getInstance()->db();

        $threshold = (float) $request->get('threshold', 10);

        $deviations = $db->select(
            "SELECT iph.item_id, i.name_ar as item_name, i.sku, s.name_ar as supplier_name,
                    iph.price as actual_price, iph.effective_date,
                    (SELECT AVG(price) FROM item_price_history WHERE item_id = iph.item_id AND price_type = 'purchase') as avg_price,
                    ROUND(((iph.price - (SELECT AVG(price) FROM item_price_history WHERE item_id = iph.item_id AND price_type = 'purchase'))
                    / NULLIF((SELECT AVG(price) FROM item_price_history WHERE item_id = iph.item_id AND price_type = 'purchase'), 0)) * 100, 1) as deviation_pct
             FROM item_price_history iph
             JOIN inventory_items i ON i.id = iph.item_id
             LEFT JOIN suppliers s ON s.id = iph.supplier_id
             WHERE iph.price_type = 'purchase'
             HAVING ABS(deviation_pct) > ?
             ORDER BY ABS(deviation_pct) DESC
             LIMIT 100",
            [$threshold]
        );

        return $this->view('Procurement.Views.reports.price_deviation', [
            'deviations' => $deviations,
            'threshold' => $threshold,
        ]);
    }
}
