<?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;
use App\Modules\Procurement\Services\QuoteService;

class QuoteController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('procurement.quote.view');
        $db = App::getInstance()->db();

        $status = $request->get('status', '');
        $where = '1=1';
        $params = [];

        if ($status) {
            $where .= ' AND q.status = ?';
            $params[] = $status;
        }

        $quotes = $db->select(
            "SELECT q.*, s.name_ar as supplier_name, s.code as supplier_code
             FROM supplier_price_quotes q
             JOIN suppliers s ON s.id = q.supplier_id
             WHERE {$where}
             ORDER BY q.created_at DESC",
            $params
        );

        return $this->view('Procurement.Views.quotes.index', [
            'quotes' => $quotes,
            'status' => $status,
        ]);
    }

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

        $requisitionId = (int) $request->get('requisition_id', 0);
        $requisition = null;
        $requisitionItems = [];

        if ($requisitionId) {
            $requisition = $db->selectOne("SELECT * FROM purchase_requisitions WHERE id = ?", [$requisitionId]);
            $requisitionItems = $db->select(
                "SELECT pri.*, i.name_ar as item_name, i.sku
                 FROM purchase_requisition_items pri
                 JOIN inventory_items i ON i.id = pri.item_id
                 WHERE pri.requisition_id = ?",
                [$requisitionId]
            );
        }

        $suppliers = $db->select("SELECT id, name_ar, code FROM suppliers WHERE is_archived = 0 AND is_active = 1 ORDER BY name_ar");
        $requisitions = $db->select("SELECT id, requisition_number, status FROM purchase_requisitions WHERE status = 'approved' ORDER BY created_at DESC LIMIT 50");

        return $this->view('Procurement.Views.quotes.request_form', [
            'requisition' => $requisition,
            'requisitionItems' => $requisitionItems,
            'suppliers' => $suppliers,
            'requisitions' => $requisitions,
        ]);
    }

    public function storeRequest(Request $request): Response
    {
        $this->authorize('procurement.quote.create');

        $requisitionId = (int) $request->post('requisition_id');
        $supplierIds = $request->post('supplier_ids', []);

        if (empty($supplierIds)) {
            return $this->redirect('/procurement/quotes/request?requisition_id=' . $requisitionId)->withError('يجب اختيار مورد واحد على الأقل');
        }

        $result = QuoteService::createQuoteRequest($requisitionId, $supplierIds);

        if (!$result['success']) {
            return $this->redirect('/procurement/quotes/request?requisition_id=' . $requisitionId)->withError($result['error']);
        }

        return $this->redirect('/procurement/quotes')->withSuccess('تم إرسال طلبات عروض الأسعار بنجاح — عدد: ' . count($result['quote_ids']));
    }

    public function recordResponse(Request $request, string $id): Response
    {
        $this->authorize('procurement.quote.create');
        $db = App::getInstance()->db();

        $quote = $db->selectOne(
            "SELECT q.*, s.name_ar as supplier_name
             FROM supplier_price_quotes q
             JOIN suppliers s ON s.id = q.supplier_id
             WHERE q.id = ?",
            [(int) $id]
        );

        if (!$quote) {
            return $this->redirect('/procurement/quotes')->withError('عرض السعر غير موجود');
        }

        $items = $db->select(
            "SELECT qi.*, i.name_ar as item_name, i.sku
             FROM supplier_quote_items qi
             JOIN inventory_items i ON i.id = qi.item_id
             WHERE qi.quote_id = ?",
            [(int) $id]
        );

        return $this->view('Procurement.Views.quotes.response_form', [
            'quote' => $quote,
            'items' => $items,
        ]);
    }

    public function storeResponse(Request $request, string $id): Response
    {
        $this->authorize('procurement.quote.create');

        $itemIds = $request->post('quote_item_ids', []);
        $unitPrices = $request->post('unit_prices', []);
        $quantities = $request->post('quantities', []);
        $deliveryDays = $request->post('delivery_days', []);

        $items = [];
        for ($i = 0; $i < count($itemIds); $i++) {
            $items[] = [
                'quote_item_id' => (int) $itemIds[$i],
                'unit_price' => $unitPrices[$i] ?? '0',
                'quantity' => $quantities[$i] ?? '0',
                'delivery_days' => $deliveryDays[$i] ?? null,
            ];
        }

        $terms = [
            'delivery_terms' => $request->post('delivery_terms'),
            'payment_terms' => $request->post('payment_terms'),
            'expiry_date' => $request->post('expiry_date'),
        ];

        $result = QuoteService::recordQuoteResponse((int) $id, $items, $terms);

        if (!$result['success']) {
            return $this->redirect('/procurement/quotes/' . $id . '/response')->withError($result['error']);
        }

        return $this->redirect('/procurement/quotes')->withSuccess('تم تسجيل رد عرض السعر بنجاح');
    }

    public function compare(Request $request): Response
    {
        $this->authorize('procurement.quote.evaluate');

        $requisitionId = (int) $request->get('requisition_id');
        $comparison = QuoteService::getComparisonData($requisitionId);

        $db = App::getInstance()->db();
        $requisition = $db->selectOne("SELECT * FROM purchase_requisitions WHERE id = ?", [$requisitionId]);

        return $this->view('Procurement.Views.quotes.compare', [
            'requisition' => $requisition,
            'comparison' => $comparison,
        ]);
    }

    public function evaluate(Request $request): Response
    {
        $this->authorize('procurement.quote.evaluate');

        $requisitionId = (int) $request->post('requisition_id');
        $winningQuoteId = (int) $request->post('winning_quote_id');
        $justification = (string) $request->post('justification');

        $result = QuoteService::evaluateQuotes($requisitionId, $winningQuoteId, $justification);

        if (!$result['success']) {
            return $this->redirect('/procurement/quotes/compare?requisition_id=' . $requisitionId)->withError($result['error']);
        }

        return $this->redirect('/procurement/quotes')->withSuccess('تم تقييم واختيار عرض السعر الفائز');
    }

    public function convertToPo(Request $request, string $evaluationId): Response
    {
        $this->authorize('procurement.pr.convert');

        $result = QuoteService::convertToPurchaseOrder((int) $evaluationId);

        if (!$result['success']) {
            return $this->redirect('/procurement/quotes')->withError($result['error']);
        }

        return $this->redirect('/inventory/purchase-orders/' . $result['po_id'])->withSuccess('تم إنشاء أمر الشراء بنجاح — رقم: ' . $result['po_number']);
    }
}
