<?php

namespace App\Http\Controllers\User;


use App\Http\Controllers\Controller;
use App\Models\User\Purchase;
use App\Models\User\PurchasePayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User\Line;
use App\Models\User\Member;
use App\Models\User\PurchaseItem;

class PurchasePaymentController extends Controller
{
    public function index()
    {
        return view('user.purchase_payments.index');
    }
public function searchLine(Request $request)
{
    $q = $request->q;

    if (!$q) {
        return response()->json([]);
    }

    return Line::where('name', 'like', "%{$q}%")
        ->orderBy('name')
        ->limit(10)
        ->get(['id', 'name']);
}
    // public function getSupplierBalance(Request $request)
    // {
    //     $supplierId = $request->supplier_id;
    //     $date = $request->payment_date;

    //     $totalPurchase = Purchase::where('supplier_id', $supplierId)
    //         ->whereDate('purchase_date', '<=', $date)
    //         ->sum('total_amount');

    //     $totalPaid = PurchasePayment::where('supplier_id', $supplierId)
    //         ->whereDate('payment_date', '<=', $date)
    //         ->sum('paid_amount');

    //     return response()->json([
    //         'total' => $totalPurchase,
    //         'paid' => $totalPaid,
    //         'balance' => $totalPurchase - $totalPaid
    //     ]);
    // }
    private function getSupplierBalanceAmount($userId, $supplierId, $lineId, $date)
{
    // Total purchases till date
    $totalPurchase = Purchase::where('user_id', $userId)
        ->where('supplier_id', $supplierId)
        ->where('line_id', $lineId)
        ->whereDate('date', '<=', $date)
        ->sum('total_amount');
       
   $totalpaidamount = Purchase::where('user_id', $userId)
        ->where('supplier_id', $supplierId)
        ->where('line_id', $lineId)
        ->whereDate('date', '<=', $date)
   
        ->sum('paid_amount');
    // Total payments till date
 

    return max(0, $totalPurchase - $totalpaidamount);
}

public function store(Request $request)
{
    $request->validate([
        'payment_date' => 'required|date',
        'line_id'      => 'required|integer',
        'line_name'    => 'required|string',
        'supplier_id'  => 'required|integer',
        'supplier_name' => 'required|string',
        'paid_amount'  => 'required|numeric|min:1',
        'description'  => 'nullable|string'
    ]);

    $userId = session('user_id');

    // 1️⃣ Get current balance till payment date
    $balance = $this->getSupplierBalanceAmount(
        $userId,
        $request->supplier_id,
        $request->line_id,
        $request->payment_date
    );

    // 2️⃣ Prevent over-payment
    if ($request->paid_amount > $balance) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Paid amount exceeds available balance'
        ], 422);
    }

    DB::transaction(function () use ($request, $userId) {

        // 3️⃣ Save payment entry
        PurchasePayment::create([
            'user_id'      => $userId,
            'payment_date' => $request->payment_date,
            'line_id'      => $request->line_id,
            'line_name'    => $request->line_name,
            'supplier_id'  => $request->supplier_id,
            'supplier_name' => $request->supplier_name,
            'description'  => $request->description,
            'paid_amount'  => $request->paid_amount,
        ]);

        // 4️⃣ Apply payment to purchases (FIFO)
        $remainingAmount = $request->paid_amount;

        $purchases = Purchase::where('user_id', $userId)
            ->where('supplier_id', $request->supplier_id)
            ->where('line_id', $request->line_id)
            ->whereDate('date', '<=', $request->payment_date)
            ->whereColumn('paid_amount', '<', 'total_amount')
            ->orderBy('date')   // oldest first
            ->orderBy('id')
            ->lockForUpdate()
            ->get();

        foreach ($purchases as $purchase) {

            if ($remainingAmount <= 0) {
                break;
            }

            $due = $purchase->total_amount - $purchase->paid_amount;

            if ($remainingAmount >= $due) {
                // fully settle this purchase
                $purchase->paid_amount += $due;
                $remainingAmount -= $due;
            } else {
                // partial payment
                $purchase->paid_amount += $remainingAmount;
                $remainingAmount = 0;
            }

            $purchase->save();
        }
    });

    return response()->json([
        'status'  => 'success',
        'message' => 'Payment saved and purchases updated successfully'
    ]);
}

      public function search(Request $request)
{
    $q = trim($request->query('q', ''));

    if ($q === '') {
        return response()->json([]);
    }

    $userId = session('user_id');

    $results = Line::where('user_id', $userId)
        ->where('type', 'Supplier')
        ->where('line_name', 'like', "{$q}%")
        ->limit(15)
        ->get(['line_id', 'line_name'])
        ->map(function ($r) {
            return [
                'id'        => $r->line_id,
                'name'      => $r->line_name,  // must match JS key
            ];
        });

    return response()->json($results);
}
 public function searchPerson(Request $request)
    {
        $q = (string) $request->query('q', '');
        if ($q === '') {
            return response()->json([]);
        }

        $userId = session('user_id');

        $results = Member::where('user_id', $userId)
            ->where('type', 'Supplier')
            ->where(function ($b) use ($q) {
                $b->where('name', 'like', "{$q}%");
                    // ->orWhere('phone', 'like', "%{$q}%")
                    // ->orWhere('address', 'like', "%{$q}%");
            })
            ->limit(15)
            ->get(['id', 'name', 'address', 'phone'])
            ->map(function ($r) {
                return [
                    'member_id'   => $r->id,
                    'member_name' => $r->name,
                    'id'          => $r->id,
                    'name'        => $r->name,
                    'address'     => $r->address ?? '',
                    'phone'       => $r->phone ?? '',
                ];
            });

        return response()->json($results);
    }
    public function getSupplierBalance(Request $request)
{
    $lineId = $request->line_id;
    $supplierId = $request->supplier_id;
    $date = $request->payment_date;

    if(!$lineId || !$supplierId || !$date){
        return response()->json([
            'total'=>0, 'paid'=>0, 'balance'=>0
        ]);
    }
 $userId = session('user_id');
    // Get total purchase amount for selected supplier + line till date
    $totalPurchase = Purchase::where('supplier_id', $supplierId)
        ->where('line_id', $lineId)
        ->where('user_id', $userId)
        ->whereDate('date', '<=', $date)

        ->sum('total_amount');

    // Get total paid till date
 $totalPaid = Purchase::where('supplier_id', $supplierId)
        ->where('line_id', $lineId)
        ->where('user_id', $userId)
        ->whereDate('date', '<=', $date)

        ->sum('paid_amount');

    return response()->json([
        'total' => $totalPurchase,
        'paid' => $totalPaid,
        'balance' => $totalPurchase - $totalPaid
    ]);
}

}
