<?php

namespace Modules\PurchaseRequisition\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\PurchaseRequisition\Entities\PrSupplierResponse;
use Modules\PurchaseRequisition\Entities\PrSupplierProduct;
use Modules\PurchaseRequisition\Entities\PrCurrency;
use Modules\PurchaseRequisition\Entities\Services\CalculationService;
use DB;

class PrSupplierController extends Controller
{
    protected $calculationService;

    public function __construct(CalculationService $calculationService)
    {
        $this->calculationService = $calculationService;
    }

    /**
     * Show supplier response page (public, no auth required).
     *
     * @param string $token
     * @return \Illuminate\View\View
     */
    public function show($token)
    {
        $lang = in_array(request('lang'), ['en', 'zh']) ? request('lang') : 'en';
        \App::setLocale($lang);

        $response = PrSupplierResponse::with([
                'prRequest.products.product',
                'prRequest.products.variation',
                'supplier',
                'currency'
            ])
            ->byToken($token)
            ->firstOrFail();

        // Check if link is accessible - show read-only view for submitted/approved responses
        if (in_array($response->status, ['submitted', 'approved'])) {
            // Load supplier products for display
            $response->load('supplierProducts.prProduct.product', 'supplierProducts.prProduct.variation');

            $supplierProducts = [];
            foreach ($response->supplierProducts as $supplierProduct) {
                $supplierProducts[] = [
                    'pr_product' => $supplierProduct->prProduct,
                    'supplier_product' => $supplierProduct,
                ];
            }

            return view('purchaseRequisition::supplier.submitted', compact('response', 'supplierProducts'));
        }

        // Get currencies
        $currencies = PrCurrency::forBusiness($response->business_id)
            ->active()
            ->get();

        // Get or create supplier products
        $supplierProducts = [];
        foreach ($response->prRequest->products as $prProduct) {
            $supplierProduct = PrSupplierProduct::firstOrCreate(
                [
                    'pr_supplier_response_id' => $response->id,
                    'pr_product_id' => $prProduct->id,
                ],
                [
                    'business_id' => $response->business_id,
                    'available_qty' => 0,
                    'supplier_price' => 0,
                    'converted_price_egp' => 0,
                ]
            );

            $supplierProducts[] = [
                'id' => $supplierProduct->id,
                'pr_product' => $prProduct,
                'supplier_product' => $supplierProduct,
            ];
        }

        return view('purchaseRequisition::supplier.response', compact('response', 'currencies', 'supplierProducts'));
    }

    /**
     * Save supplier response (can re-access).
     *
     * @param Request $request
     * @param string $token
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, $token)
    {
        $response = PrSupplierResponse::byToken($token)->firstOrFail();

        // Check if already submitted
        if ($response->status == 'submitted') {
            return redirect()->back()->with('error', 'This response has already been submitted and cannot be edited.');
        }

        $request->validate([
            'currency_id' => 'required|exists:pr_currencies,id',
            'products' => 'required|array',
            'products.*.available_qty' => 'nullable|numeric|min:0',
            'products.*.supplier_price' => 'nullable|numeric|min:0',
        ]);

        try {
            DB::beginTransaction();

            // Update currency
            $response->update(['currency_id' => $request->currency_id]);

            // Update supplier products
            foreach ($request->products as $productId => $productData) {
                $supplierProduct = PrSupplierProduct::findOrFail($productId);

                // Validate available_qty <= required_qty
                if (isset($productData['available_qty']) && $productData['available_qty'] > $supplierProduct->prProduct->required_quantity) {
                    throw new \Exception('Available quantity cannot exceed required quantity.');
                }

                // Calculate converted price
                $convertedPrice = $this->calculationService->convertToEgp(
                    $productData['supplier_price'] ?? 0,
                    $request->currency_id
                );

                $supplierProduct->update([
                    'available_qty' => $productData['available_qty'] ?? 0,
                    'supplier_price' => $productData['supplier_price'] ?? 0,
                    'converted_price_egp' => $convertedPrice,
                    'supplier_notes' => $productData['supplier_notes'] ?? null,
                ]);
            }

            DB::commit();

            return redirect()->back()->with('success', 'Response saved successfully. You can continue editing.');

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Submit final supplier response (locks editing).
     *
     * @param Request $request
     * @param string $token
     * @return \Illuminate\Http\RedirectResponse
     */
    public function submit(Request $request, $token)
    {
        $response = PrSupplierResponse::byToken($token)->firstOrFail();

        // Check if already submitted
        if ($response->status == 'submitted') {
            return redirect()->back()->with('error', 'This response has already been submitted.');
        }

        $request->validate([
            'currency_id' => 'required|exists:pr_currencies,id',
            'products' => 'required|array',
        ]);

        try {
            DB::beginTransaction();

            // Save data first (same as save method)
            $response->update(['currency_id' => $request->currency_id]);

            foreach ($request->products as $productId => $productData) {
                $supplierProduct = PrSupplierProduct::findOrFail($productId);

                // Validate
                if (isset($productData['available_qty']) && $productData['available_qty'] > $supplierProduct->prProduct->required_quantity) {
                    throw new \Exception('Available quantity cannot exceed required quantity.');
                }

                $convertedPrice = $this->calculationService->convertToEgp(
                    $productData['supplier_price'] ?? 0,
                    $request->currency_id
                );

                $supplierProduct->update([
                    'available_qty' => $productData['available_qty'] ?? 0,
                    'supplier_price' => $productData['supplier_price'] ?? 0,
                    'converted_price_egp' => $convertedPrice,
                    'supplier_notes' => $productData['supplier_notes'] ?? null,
                ]);
            }

            // Mark as submitted
            $response->update([
                'status' => 'submitted',
                'submitted_at' => now(),
            ]);

            // Update PR status
            $prRequest = $response->prRequest;

            // Check if all supplier responses are submitted
            $allSubmitted = $prRequest->supplierResponses()
                ->whereIn('status', ['pending'])
                ->count() == 0;

            if ($allSubmitted) {
                $prRequest->update(['status' => 'pending_approval']);
            }

            DB::commit();

            $lang = in_array($request->input('lang'), ['en', 'zh']) ? $request->input('lang') : 'en';
            $redirectUrl = route('supplier.submitted', $token) . ($lang !== 'en' ? '?lang=' . $lang : '');
            return redirect($redirectUrl)->with('success', 'Response submitted successfully. You can no longer edit this response.');

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Show submitted confirmation page.
     *
     * @param string $token
     * @return \Illuminate\View\View
     */
    public function submitted($token)
    {
        $lang = in_array(request('lang'), ['en', 'zh']) ? request('lang') : 'en';
        \App::setLocale($lang);

        $response = PrSupplierResponse::with([
                'supplier',
                'prRequest.products.product',
                'prRequest.products.variation',
                'supplierProducts.prProduct.product',
                'supplierProducts.prProduct.variation',
                'currency'
            ])
            ->byToken($token)
            ->firstOrFail();

        // Only allow viewing if submitted or approved
        if (!in_array($response->status, ['submitted', 'approved'])) {
            abort(404, 'This requisition is not available for viewing.');
        }

        // Build supplier products array for display
        $supplierProducts = [];
        foreach ($response->supplierProducts as $supplierProduct) {
            $supplierProducts[] = [
                'pr_product' => $supplierProduct->prProduct,
                'supplier_product' => $supplierProduct,
            ];
        }

        return view('purchaseRequisition::supplier.submitted', compact('response', 'supplierProducts'));
    }
}
