<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use DB;
use Illuminate\Support\Facades\Schema;  //special
use Carbon\Carbon;
use Auth;


class LoanController extends Controller
{
    public function storeLoan(Request $request)
    {
        DB::table('loans')->insert([
            'employee_id' => $request->employee_id,
            'amount' => $request->amount,
            'date' => $request->date,
            'note' => $request->note
        ]);

        return back()->with('success', 'Loan Added');
    }

  public function addPayment(Request $request)
  {
      $loan = DB::table('loans')->where('id', $request->loan_id)->first();

      $paid = DB::table('loan_payments')
          ->where('loan_id', $request->loan_id)
          ->sum('amount');

      $newTotal = $paid + $request->amount;

      if ($newTotal > $loan->amount) {
          return back()->with('error', 'Payment exceeds loan amount!');
      }

      DB::table('loan_payments')->insert([
          'loan_id' => $request->loan_id,
          'amount' => $request->amount,
          'date' => $request->date,
          'note' => $request->note
      ]);

      return back()->with('success','Payment Added');
  }
}
