<?php

namespace App\Http\Controllers;

use App\Models\Supplier;
use App\Models\SupplierEvaluation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SupplierEvaluationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $companyId = auth()->user()->company_id;

        $evaluations = SupplierEvaluation::whereHas('supplier', function ($query) use ($companyId) {
            $query->where('company_id', $companyId);
        })
            ->with(['supplier', 'createdBy'])
            ->orderBy('evaluation_date', 'desc')
            ->paginate(15);

        return view('inventory.supplier_evaluations.index', compact('evaluations'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $companyId = auth()->user()->company_id;
        $suppliers = Supplier::where('company_id', $companyId)->orderBy('name')->get();

        return view('inventory.supplier_evaluations.create', compact('suppliers'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'evaluation_date' => 'required|date',
            'quality_score' => 'required|integer|min:1|max:10',
            'delivery_score' => 'required|integer|min:1|max:10',
            'price_score' => 'required|integer|min:1|max:10',
            'communication_score' => 'required|integer|min:1|max:10',
            'notes' => 'nullable|string',
        ]);

        // التحقق من أن المورد ينتمي للشركة الحالية
        $supplier = Supplier::findOrFail($request->supplier_id);
        if ($supplier->company_id != auth()->user()->company_id) {
            return redirect()->back()->with('error', 'لا يمكنك تقييم مورد لا ينتمي لشركتك');
        }

        $evaluation = new SupplierEvaluation();
        $evaluation->supplier_id = $request->supplier_id;
        $evaluation->evaluation_date = $request->evaluation_date;
        $evaluation->quality_score = $request->quality_score;
        $evaluation->delivery_score = $request->delivery_score;
        $evaluation->price_score = $request->price_score;
        $evaluation->communication_score = $request->communication_score;
        $evaluation->overall_score = ($request->quality_score + $request->delivery_score + $request->price_score + $request->communication_score) / 4;
        $evaluation->notes = $request->notes;
        $evaluation->created_by = Auth::id();
        $evaluation->save();

        // تحديث متوسط تقييم المورد
        $this->updateSupplierAverageRating($supplier);

        return redirect()->route('supplier-evaluations.index')
            ->with('success', 'تم إضافة تقييم المورد بنجاح');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\SupplierEvaluation  $supplierEvaluation
     * @return \Illuminate\Http\Response
     */
    public function show(SupplierEvaluation $supplierEvaluation)
    {
        // التحقق من أن التقييم ينتمي للشركة الحالية
        if ($supplierEvaluation->supplier->company_id != auth()->user()->company_id) {
            return redirect()->route('supplier-evaluations.index')
                ->with('error', 'لا يمكنك عرض تقييم لا ينتمي لشركتك');
        }

        $supplierEvaluation->load(['supplier', 'createdBy']);

        return view('inventory.supplier_evaluations.show', compact('supplierEvaluation'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\SupplierEvaluation  $supplierEvaluation
     * @return \Illuminate\Http\Response
     */
    public function edit(SupplierEvaluation $supplierEvaluation)
    {
        // التحقق من أن التقييم ينتمي للشركة الحالية
        if ($supplierEvaluation->supplier->company_id != auth()->user()->company_id) {
            return redirect()->route('supplier-evaluations.index')
                ->with('error', 'لا يمكنك تعديل تقييم لا ينتمي لشركتك');
        }

        $companyId = auth()->user()->company_id;
        $suppliers = Supplier::where('company_id', $companyId)->orderBy('name')->get();

        return view('inventory.supplier_evaluations.edit', compact('supplierEvaluation', 'suppliers'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\SupplierEvaluation  $supplierEvaluation
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, SupplierEvaluation $supplierEvaluation)
    {
        // التحقق من أن التقييم ينتمي للشركة الحالية
        if ($supplierEvaluation->supplier->company_id != auth()->user()->company_id) {
            return redirect()->route('supplier-evaluations.index')
                ->with('error', 'لا يمكنك تعديل تقييم لا ينتمي لشركتك');
        }

        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'evaluation_date' => 'required|date',
            'quality_score' => 'required|integer|min:1|max:10',
            'delivery_score' => 'required|integer|min:1|max:10',
            'price_score' => 'required|integer|min:1|max:10',
            'communication_score' => 'required|integer|min:1|max:10',
            'notes' => 'nullable|string',
        ]);

        // التحقق من أن المورد ينتمي للشركة الحالية
        $supplier = Supplier::findOrFail($request->supplier_id);
        if ($supplier->company_id != auth()->user()->company_id) {
            return redirect()->back()->with('error', 'لا يمكنك تقييم مورد لا ينتمي لشركتك');
        }

        $oldSupplierId = $supplierEvaluation->supplier_id;

        $supplierEvaluation->supplier_id = $request->supplier_id;
        $supplierEvaluation->evaluation_date = $request->evaluation_date;
        $supplierEvaluation->quality_score = $request->quality_score;
        $supplierEvaluation->delivery_score = $request->delivery_score;
        $supplierEvaluation->price_score = $request->price_score;
        $supplierEvaluation->communication_score = $request->communication_score;
        $supplierEvaluation->overall_score = ($request->quality_score + $request->delivery_score + $request->price_score + $request->communication_score) / 4;
        $supplierEvaluation->notes = $request->notes;
        $supplierEvaluation->save();

        // تحديث متوسط تقييم المورد الحالي
        $this->updateSupplierAverageRating($supplier);

        // إذا تم تغيير المورد، قم بتحديث متوسط تقييم المورد السابق أيضًا
        if ($oldSupplierId != $request->supplier_id) {
            $oldSupplier = Supplier::find($oldSupplierId);
            if ($oldSupplier) {
                $this->updateSupplierAverageRating($oldSupplier);
            }
        }

        return redirect()->route('supplier-evaluations.index')
            ->with('success', 'تم تحديث تقييم المورد بنجاح');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\SupplierEvaluation  $supplierEvaluation
     * @return \Illuminate\Http\Response
     */
    public function destroy(SupplierEvaluation $supplierEvaluation)
    {
        // التحقق من أن التقييم ينتمي للشركة الحالية
        if ($supplierEvaluation->supplier->company_id != auth()->user()->company_id) {
            return redirect()->route('supplier-evaluations.index')
                ->with('error', 'لا يمكنك حذف تقييم لا ينتمي لشركتك');
        }

        $supplier = $supplierEvaluation->supplier;

        $supplierEvaluation->delete();

        // تحديث متوسط تقييم المورد
        $this->updateSupplierAverageRating($supplier);

        return redirect()->route('supplier-evaluations.index')
            ->with('success', 'تم حذف تقييم المورد بنجاح');
    }

    /**
     * تحديث متوسط تقييم المورد
     *
     * @param  \App\Models\Supplier  $supplier
     * @return void
     */
    private function updateSupplierAverageRating(Supplier $supplier)
    {
        $averageRating = SupplierEvaluation::where('supplier_id', $supplier->id)
            ->avg('overall_score');

        $supplier->rating = $averageRating ?? 0;
        $supplier->save();
    }
}
