<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VendorPaymentHistoryController extends Controller
{
    // Display all payment histories
    public function index()
    {
        $paymentHistories = DB::table('vendor_payment_histories')->get();
         $vendors = DB::table('vendors')
        ->join('users', 'vendors.user_id', '=', 'users.user_id')
        ->select('vendors.*', 'users.name as user_name', 'users.email as user_email', 'users.wallet as user_wallet')
        ->get();
return view('vendor_payment_histories.index', compact('paymentHistories', 'vendors'));
       
    }

    // Store new payment history
    public function store(Request $request)
{
    $validated = $request->validate([
        'vendor_id' => 'required|exists:vendors,user_id',
        'amount_paid' => 'required|numeric|min:0',
        'balance' => 'required|numeric|min:0',
        'payment_date' => 'required|date',
        'payment_method' => 'required|string|max:50',
        'remarks' => 'nullable|string|max:255',
    ]);

    // Fetch the vendor's wallet balance
    $vendor = DB::table('vendors')
        ->join('users', 'vendors.user_id', '=', 'users.user_id')
        ->where('vendors.user_id', $validated['vendor_id'])
        ->select('users.wallet')
        ->first();

    if (!$vendor) {
        return back()->withErrors(['vendor_id' => 'Vendor not found.']);
    }

    // Check if the amount_paid is greater than the wallet balance
    if ($validated['amount_paid'] > $vendor->wallet) {
        return back()->withErrors(['amount_paid' => 'Amount paid exceeds wallet balance.']);
    }

    // Update the vendor's wallet balance
    $newWalletBalance = $vendor->wallet - $validated['amount_paid'];

    DB::table('users')
        ->where('user_id', $validated['vendor_id'])
        ->update(['wallet' => $newWalletBalance]);

    // Insert the payment history
    DB::table('vendor_payment_histories')->insert([
        'vendor_id' => $validated['vendor_id'],
        'amount_paid' => $validated['amount_paid'],
        'balance' => $validated['balance'],
        'payment_date' => $validated['payment_date'],
        'payment_method' => $validated['payment_method'],
        'remarks' => $validated['remarks'],
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    return back()->with('success', 'Payment history added successfully, and wallet balance updated.');
}


    // Delete payment history
    public function destroy($id)
    {
        DB::table('vendor_payment_histories')->where('id', $id)->delete();
        return back()->with('success', 'Payment history deleted successfully.');
    }
}
