<?php

namespace App\Service\Customer;

use App\Models\CustomerAdvancePaymentMaster;
use App\Models\CustomerAdvancePaymentDetail;
use App\Models\CustomerPaymentCollection;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CustomerAdvancePaymentService
{
    public static function store($data)
    {
        DB::transaction(function () use ($data) {
            try {
                $collect = collect($data);
                
                // Calculate totals
                $totalAmount = array_reduce($collect['list'] ?? [], function ($acc, $item) {
                    return $acc + ($item['total'] ?? 0);
                }, 0);

                $totalPaid = 0;
                if (isset($collect['payments']) && is_array($collect['payments'])) {
                    $totalPaid = array_sum(array_column($collect['payments'], 'amount'));
                }

                // Create master record
                $paymentDate = $collect['advance_payment_date'] 
                    ? Carbon::parse($collect['advance_payment_date']) 
                    : Carbon::now();

                $master = CustomerAdvancePaymentMaster::create([
                    'reference_no' => $collect['reference_no'],
                    'receipt_no' => $collect['receipt_no'] ?? null,
                    'advance_payment_date' => $paymentDate,
                    'customer_id' => $collect['customer_id'] ?? null,
                    'warehouse_id' => $collect['warehouse_id'] ?? null,
                    'total_amount' => $totalAmount,
                    'total_paid' => $totalPaid,
                    'notes' => $collect['notes'] ?? null,
                    'created_by' => Auth::id(),
                ]);

                // Create detail records
                if (isset($collect['list']) && is_array($collect['list'])) {
                    foreach ($collect['list'] as $item) {
                        CustomerAdvancePaymentDetail::create([
                            'advance_payment_master_id' => $master->id,
                            'product_id' => $item['product_id'],
                            'attribute_id' => $item['attribute_id'],
                            'quantity' => $item['quantity'] ?? 0,
                            'price' => $item['price'] ?? 0,
                            'total' => $item['total'] ?? 0,
                            'invoice_type' => $item['type'] ?? 'MRP',
                        ]);
                    }
                }

                // Create payment records
                if (isset($collect['payments']) && is_array($collect['payments'])) {
                    foreach ($collect['payments'] as $payment) {
                        if (isset($payment['amount']) && $payment['amount'] > 0) {
                            CustomerPaymentCollection::create([
                                'customer_id' => $collect['customer_id'] ?? null,
                                'date' => Carbon::parse($payment['date'] ?? $collect['advance_payment_date']),
                                'payment' => $payment['amount'],
                                'payment_type' => $payment['method'] ?? 'cash',
                                'payment_id' => !empty($payment['account']) ? $payment['account'] : null,
                                'advance_payment_master_id' => $master->id,
                                'warehouse_id' => $collect['warehouse_id'] ?? null,
                                'status' => 'advance',
                                'order_no' => $payment['collection_reference'] ?? null,
                                'notes' => $payment['notes'] ?? null,
                                'collection_reference' => $payment['collection_reference'] ?? null,
                            ]);
                        }
                    }
                }
            } catch (\Exception $e) {
                DB::rollBack();
                throw $e;
            }
        });
    }

    public static function update($data, $id)
    {
        DB::transaction(function () use ($data, $id) {
            try {
                $collect = collect($data);

                // Calculate totals
                $totalAmount = array_reduce($collect['list'] ?? [], function ($acc, $item) {
                    return $acc + ($item['total'] ?? 0);
                }, 0);

                $totalPaid = 0;
                if (isset($collect['payments']) && is_array($collect['payments'])) {
                    $totalPaid = array_sum(array_column($collect['payments'], 'amount'));
                }

                // Update master record
                $master = CustomerAdvancePaymentMaster::findOrFail($id);
                $paymentDate = $collect['advance_payment_date'] 
                    ? Carbon::parse($collect['advance_payment_date']) 
                    : $master->advance_payment_date;

                $master->update([
                    'receipt_no' => $collect['receipt_no'] ?? null,
                    'advance_payment_date' => $paymentDate,
                    'customer_id' => $collect['customer_id'] ?? null,
                    'warehouse_id' => $collect['warehouse_id'] ?? null,
                    'total_amount' => $totalAmount,
                    'total_paid' => $totalPaid,
                    'notes' => $collect['notes'] ?? null,
                    'updated_by' => Auth::id(),
                ]);

                // Delete old details
                CustomerAdvancePaymentDetail::where('advance_payment_master_id', $id)->delete();

                // Create new detail records
                if (isset($collect['list']) && is_array($collect['list'])) {
                    foreach ($collect['list'] as $item) {
                        CustomerAdvancePaymentDetail::create([
                            'advance_payment_master_id' => $master->id,
                            'product_id' => $item['product_id'],
                            'attribute_id' => $item['attribute_id'],
                            'quantity' => $item['quantity'] ?? 0,
                            'price' => $item['price'] ?? 0,
                            'total' => $item['total'] ?? 0,
                            'invoice_type' => $item['type'] ?? 'MRP',
                        ]);
                    }
                }

                // Delete old payments
                CustomerPaymentCollection::where('advance_payment_master_id', $id)->delete();

                // Create new payment records
                if (isset($collect['payments']) && is_array($collect['payments'])) {
                    foreach ($collect['payments'] as $payment) {
                        if (isset($payment['amount']) && $payment['amount'] > 0) {
                            CustomerPaymentCollection::create([
                                'customer_id' => $collect['customer_id'] ?? null,
                                'date' => Carbon::parse($payment['date'] ?? $collect['advance_payment_date']),
                                'payment' => $payment['amount'],
                                'payment_type' => $payment['method'] ?? 'cash',
                                'payment_id' => !empty($payment['account']) ? $payment['account'] : null,
                                'advance_payment_master_id' => $master->id,
                                'warehouse_id' => $collect['warehouse_id'] ?? null,
                                'status' => 'advance',
                                'order_no' => $payment['collection_reference'] ?? null,
                                'notes' => $payment['notes'] ?? null,
                                'collection_reference' => $payment['collection_reference'] ?? null,
                            ]);
                        }
                    }
                }
            } catch (\Exception $e) {
                DB::rollBack();
                throw $e;
            }
        });
    }
}

