<?php

namespace App\Http\Controllers;

use App\Models\PaymentStatusModel;
use App\Models\ProductDetailsModel;
use App\Models\ProductPaymentModel;
use App\Models\PurchaseModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductPaymentController extends Controller
{

    public function index(Request $request)
    {
        $payments_data = PurchaseModel::with('payments')
            ->where('branch_id', session('branch_id'))
            ->whereHas('payments')
            ->orderBy('id', 'desc')
            ->get();
        $payment_status = PaymentStatusModel::all();

        return view('product-payments.index', compact('payments_data', 'payment_status'));
    }

    public function add()
    {
        $purchase = PurchaseModel::doesntHave('payments')->get();

        return view('product-payments.add', compact('purchase'));
    }

    public function getPurchase($id)
    {
        $purchase = PurchaseModel::find($id);

        if (!$purchase) {
            return response()->json(['error' => 'Purchase not found'], 404);
        }

        return response()->json([
            'dueAmount' => round((float) ($purchase->due_amount ?? 0), 2),
            'totalAmount' => round((float) ($purchase->total_amount ?? 0), 2),
        ]);
    }


    public function store(Request $request)
    {
        $request->validate([
            'purchase_id' => 'required',
            'payment_type' => 'required',
            'payment_date' => 'required|date',
            'total_amount' => 'required|numeric',
            'amount' => 'required|numeric',
        ]);
        $purchase = PurchaseModel::find($request->purchase_id);

        if ($request->amount > $purchase->due_amount) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Payment amount cannot be greater than the due amount.');
        }

        $product_payment = ProductPaymentModel::create([
            'purchase_id' => $request->purchase_id,
            'payment_type' => $request->payment_type,
            'payment_date' => $request->payment_date,
            'total_amount' => $request->total_amount,
            'paid_amount' => $request->amount,
            'type' => 'paid'
        ]);

        $dueAmount = $purchase->due_amount;

        if ($request->amount >= $dueAmount) {
            $status = 'Paid';
        } elseif ($request->amount > 0 && $request->amount < $dueAmount) {
            $status = 'Partially Paid';
        } else {
            $status = 'Unpaid';
        }
        $paymentStatus = DB::table('payment_status')->where('name', $status)->first();
        $purchase->where('id', $product_payment->purchase_id)
            ->update([
                'status' => $paymentStatus->id,
                'updated_at' => now(),
            ]);

        return redirect()->route('product-payment-index')
            ->with('success', 'Payment created successfully!');
    }

    public function edit($id)
    {
        $purchase = PurchaseModel::find($id);
        $payment = ProductPaymentModel::where('purchase_id', $id)->first();

        if (!$payment) {
            return redirect()->route('product-payments.index')
                ->with('error', 'Payment not found');
        }

        $paidAmount = ProductPaymentModel::where('purchase_id', $id)
            ->whereNotIn('type', ['refund', 'loss'])
            ->sum('paid_amount');

        $totalRefunded = ProductPaymentModel::where('purchase_id', $id)
            ->where('type', 'refund')
            ->sum('paid_amount');

        $totalLoss = ProductPaymentModel::where('purchase_id', $id)
            ->where('type', 'loss')
            ->sum('paid_amount');

        $totalAmount = $purchase->total_amount;

        $totalPaidAmount = $paidAmount - $totalRefunded - $totalLoss;

        // $dueAmount = max(0, round($totalAmount - $totalPaidAmount, 2));
        $dueAmount = round($totalAmount - $totalPaidAmount, 2);

        $paymentsForProduct = ProductPaymentModel::with('product_dtls')
            ->where('purchase_id', $id)
            ->get();

        return view('product-payments.edit', compact(
            'payment',
            'purchase',
            'totalAmount',
            'totalPaidAmount',
            'dueAmount',
            'paymentsForProduct',
            'totalRefunded'
        ));
    }
    public function update(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric',
            'payment_type' => 'required',
            'payment_date' => 'required|date',
        ]);

        $id = $request->payment_id;

        if ((float) $request->totalAmount < (float) $request->amount + (float) $request->paidAmount) {
            return back()->with('error', 'Amount should be lesser than Total amount, Please try again!');
        }

        ProductPaymentModel::create([
            'purchase_id' => $id,
            'payment_type' => $request->payment_type,
            'total_amount' => $request->totalAmount,
            'paid_amount' => $request->amount,
            'payment_date' => $request->payment_date,
            'type' => 'paid'
        ]);

        $paidAmount = ProductPaymentModel::where('product_dtl_id', $id)->sum('paid_amount');
        $product_dtl = ProductDetailsModel::where('product_details_sid', $id)->first();

        if ($product_dtl) {
            if ($paidAmount >= $product_dtl->total_amount) {
                $status = 'Paid';
            } elseif ($paidAmount > 0 && $paidAmount < $product_dtl->total_amount) {
                $status = 'Partially Paid';
            } else {
                $status = 'Unpaid';
            }

            $paymentStatus = DB::table('payment_status')->where('name', $status)->first();
            if ($paymentStatus) {
                $product_dtl->update([
                    'status' => $paymentStatus->id,
                    'updated_at' => now(),
                ]);
            }
        }

        return redirect()->route('product-payment-index')
            ->with('success', 'Payment updated and a new record created successfully!');
    }

    public function delete($id)
    {
        $payments = ProductPaymentModel::where('product_dtl_id', $id)->get();

        if ($payments->isNotEmpty()) {
            $product_dtls = ProductDetailsModel::find($id);
            if ($product_dtls) {
                $product_dtls->status = 1;
                $product_dtls->save();
            }

            ProductPaymentModel::where('product_dtl_id', $id)->delete();

            return redirect()->route('product-payment-index')
                ->with('success', 'Payments deleted successfully!');
        }

        return redirect()->route('product-payment-index')
            ->with('error', 'Payments not found!');
    }
}