<?php

namespace App\Http\Controllers\Admin;

use App\Models\Sale;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Services\AccountService;
use Throwable;

class CreditDueController extends Controller
{


    public function index(Request $request)
    {


        $item = $request->item ?? 10;
        $search = $request->search;


        if (!empty($search)) {


            $credit_dues = Sale::where('company_id', NULL)->where('supplier_id', NULL)
                    ->whereNotIn('sale_type', [4,2])
                    ->where('customer_phone', 'like', '%' . $search . '%')
                    ->select('id', 'invoice_no', 'total', 'paid', 'customer_id', 'created_at', DB::raw('total - SUM(paid+discount) as due_amount '))
                    ->where(DB::raw('total - (paid+discount) '), '>', 0)
                    ->groupBy('id')->groupBy('created_at')
                    ->groupBy('total')->groupBy('paid')
                    ->groupBy('invoice_no')->groupBy('customer_id')
                    ->orderBy('id', 'desc')->with('customer:id,name,phone')->paginate($item);
        } else {
            $credit_dues = Sale::where('company_id', NULL)->where('supplier_id', NULL)
                    ->whereNotIn('sale_type', [4,2])
                    ->select('id', 'invoice_no', 'total', 'paid', 'customer_id', 'created_at', DB::raw('total - SUM(paid+discount) as due_amount '))
                    ->where(DB::raw('total - (paid+discount) '), '>', 0)
                    ->groupBy('id')->groupBy('created_at')
                    ->groupBy('total')->groupBy('paid')
                    ->groupBy('invoice_no')->groupBy('customer_id')
                    ->orderBy('id', 'desc')->with('customer:id,name,phone')->paginate($item);
        }

        return response()->json($credit_dues);
    }




    public function exportDueCustomer()
    {

        $sale_dues = Sale::where('company_id', null)->where('supplier_id',null)
                ->select('id', 'invoice_no', 'total', 'paid', 'customer_id', 'created_at', DB::raw('total - SUM(paid+discount) as due_amount '))
                ->where(DB::raw('total - (paid+discount) '), '>', 0)
                ->groupBy('id')->groupBy('created_at')
                ->groupBy('total')->groupBy('paid')
                ->groupBy('invoice_no')->groupBy('customer_id')
                ->orderBy('due_amount', 'desc')->with('customer:id,name,phone')->get();

        $total_due_amount = $sale_dues->sum('due_amount');


        return view('admin.pdf.dueList', compact('total_due_amount', 'sale_dues'));
    }



    public function  duePaid(Request $request)
    {

        $data = $request->validate([
            'sale_id' => 'required|integer',
            'balance_id' => 'required|integer',
            'amount' => 'required',
            'payable_amount' => 'required',
        ]);


        DB::beginTransaction();
        try {

            //update sale paid amount 
            $sale = Sale::findOrFail($data['sale_id']);
            $sale->paid = $sale->paid + $data['amount'];
            $sale->save();
            //store credit
            $comment = "Due paid, total due amount is " . $data['payable_amount'] .' paid  ' . $data['amount']. ' the sale invoice number is '.$sale->invoice_no ;
            AccountService::creditStore('due amount paid', $data['amount'], $data['balance_id'], null, null, $comment);

            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'paid successfully',
            ]);
        } catch (Throwable $th) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => $th->getMessage(),
            ]);
        }
    }
}
