<?php

namespace App\Http\Controllers;

use App\Models\PurchaseInvoice;
use App\Models\PurchaseInvoicePayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class PurchaseInvoicePaymentController extends Controller
{
    /**
     * عرض قائمة مدفوعات فواتير المشتريات
     */
    public function index()
    {
        $this->authorize('view_purchase_invoice_payments');

        $payments = PurchaseInvoicePayment::with(['purchaseInvoice.supplier', 'creator'])
            ->orderBy('payment_date', 'desc')
            ->paginate(15);

        return view('inventory.purchase-invoice-payments.index', compact('payments'));
    }

    /**
     * عرض تفاصيل دفعة
     */
    public function show(PurchaseInvoicePayment $payment)
    {
        $this->authorize('view_purchase_invoice_payments');

        $payment->load(['purchaseInvoice.supplier', 'creator']);

        return view('inventory.purchase-invoice-payments.show', compact('payment'));
    }

    /**
     * عرض نموذج تعديل دفعة
     */
    public function edit(PurchaseInvoicePayment $payment)
    {
        $this->authorize('edit_purchase_invoice_payments');

        $payment->load(['purchaseInvoice.supplier']);

        return view('inventory.purchase-invoice-payments.edit', compact('payment'));
    }

    /**
     * تحديث دفعة
     */
    public function update(Request $request, PurchaseInvoicePayment $payment)
    {
        $this->authorize('edit_purchase_invoice_payments');

        $purchaseInvoice = $payment->purchaseInvoice;

        $validated = $request->validate([
            'payment_date' => 'required|date',
            'amount' => [
                'required',
                'numeric',
                'min:0.01',
                function ($attribute, $value, $fail) use ($purchaseInvoice, $payment) {
                    $remainingAmount = $purchaseInvoice->remaining_amount + $payment->amount;
                    if ($value > $remainingAmount) {
                        $fail('مبلغ الدفعة يتجاوز المبلغ المتبقي من الفاتورة (' . number_format($remainingAmount, 2) . ')');
                    }
                },
            ],
            'payment_method' => 'required|string',
            'reference_number' => 'nullable|string',
            'notes' => 'nullable|string',
            'attachment' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:2048',
        ]);

        // معالجة الملف المرفق إذا وجد
        $attachmentPath = $payment->attachment;
        if ($request->hasFile('attachment')) {
            // حذف الملف القديم إذا وجد
            if ($attachmentPath) {
                Storage::disk('public')->delete($attachmentPath);
            }

            $file = $request->file('attachment');
            $fileName = 'payment_' . time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
            $attachmentPath = $file->storeAs('purchase_invoice_payments', $fileName, 'public');
        }

        DB::beginTransaction();

        try {
            // تحديث سجل الدفعة
            $payment->update([
                'payment_date' => $validated['payment_date'],
                'amount' => $validated['amount'],
                'payment_method' => $validated['payment_method'],
                'reference_number' => $validated['reference_number'] ?? null,
                'notes' => $validated['notes'] ?? null,
                'attachment' => $attachmentPath,
            ]);

            // تحديث حالة الدفع للفاتورة
            $purchaseInvoice->updatePaymentStatus();

            DB::commit();

            return redirect()->route('inventory.purchase-invoice-payments.show', $payment)
                ->with('success', 'تم تحديث الدفعة بنجاح');
        } catch (\Exception $e) {
            DB::rollBack();

            return redirect()->back()
                ->withInput()
                ->with('error', 'حدث خطأ أثناء تحديث الدفعة: ' . $e->getMessage());
        }
    }

    /**
     * حذف دفعة
     */
    public function destroy(PurchaseInvoicePayment $payment)
    {
        $this->authorize('delete_purchase_invoice_payments');

        $purchaseInvoice = $payment->purchaseInvoice;

        DB::beginTransaction();

        try {
            // حذف الملف المرفق إذا وجد
            if ($payment->attachment) {
                Storage::disk('public')->delete($payment->attachment);
            }

            // حذف سجل الدفعة
            $payment->delete();

            // تحديث حالة الدفع للفاتورة
            $purchaseInvoice->updatePaymentStatus();

            DB::commit();

            return redirect()->route('inventory.purchase-invoice-payments.index')
                ->with('success', 'تم حذف الدفعة بنجاح');
        } catch (\Exception $e) {
            DB::rollBack();

            return redirect()->back()
                ->with('error', 'حدث خطأ أثناء حذف الدفعة: ' . $e->getMessage());
        }
    }
}
