<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Expense;
use App\Models\ExpenseCategory;
use App\Models\Transaction;
use Illuminate\Support\Facades\Validator;
use Auth;

class ExpenseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $expense_category=ExpenseCategory::latest()->get();
        return view('add-expense',compact('expense_category'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
        'date' => 'required',
        'expense_category_id' => 'required',
        'payment_mode' => 'required',
        'description' => 'required',
        'amount' => 'required',
        
        ]);

        if ($validator->fails()) {
        return redirect('expense')
                 ->withErrors($validator)
                 ->withInput();
        }else{
            try {
                $data = request()->all();
                $data['created_by']=Auth::user()->id;
                $data['transaction_date']=$request->date;
                $data['expense_category_id']=$request->expense_category_id;
                $data['payment_mode']=$request->payment_mode;
                $data['description']=$request->description;
                $data['amount']=$request->amount;
                $data['type']='expense';
             
                $insert=Transaction::create($data);
                if($insert){
                    return redirect('manage-expense')->with('success','Successfully Submitted');
                }
            } catch (\Throwable $th) {
                return $th->getMessage();
            }

        }
    }

    function manage_expense(){
        $expense_category=ExpenseCategory::latest()->get();
        return view('manage-expense',compact('expense_category'));
    }
    function fetch_expense(Request $request){
        // print_r($request->expense_category_id);die;
        $user_id=Auth::user()->id;
        $result = array('data' => array());
        $report=Transaction::select('transaction.*','transaction.id','users.name as user_name','expense_category.name as cat_name')
                            ->leftjoin('users','users.id','=','transaction.created_by')
                            ->leftjoin('expense_category','expense_category.id','=','transaction.expense_category_id')->where('transaction.type','=','expense')->latest();

if(!empty($request->expense_category_id)){
        

         $report->whereIn('transaction.expense_category_id', $request->expense_category_id);

        }
        if(!empty($request->datefrom)){
         $datefrom=date('Y-m-d',strtotime($request->datefrom));

         $report->whereDate('transaction.transaction_date', '>=', $datefrom);

        }
        if (!empty($request->dateto)) {
            $dateto=date('Y-m-d',strtotime($request->dateto));
            $report->whereDate('transaction.transaction_date', '<=', $dateto);
        }
        
        

        $data=$report->get();

         $i=1;
         foreach ($data as $key => $value) {
            
            $button='';
        
            $button='<td>
                    <a  class="btn bg-gradient-info btn-sm"  href="'.url('edit-expense/'.$value['id']).'">Edit</a></td>';
                if (auth()->user()->role == 'admin' ) {
                $button.='<td> <a type="button" class="btn bg-gradient-danger btn-sm" data-id="'.$value['id'].'" id="delete-expense">Delete</a></td>';
            }
            


                $result['data'][$key] = array(
                $i,
                $value['transaction_date'],
                $value['cat_name'],
                $value['payment_mode'],
                $value['description'],
                $value['amount'],
                $value['user_name'],
                $button,
            );
       $i++;  }
     echo json_encode($result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $expense_category=ExpenseCategory::latest()->get();
        $expense=Transaction::findOrfail($id);
        return view('edit-expense',compact('expense','expense_category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         $validator = Validator::make($request->all(), [
        'date' => 'required',
        'expense_category_id' => 'required',
        'payment_mode' => 'required',
        'description' => 'required',
        'amount' => 'required',
        
        ]);

        if ($validator->fails()) {
        return redirect('edit-expense/'.$id)
                 ->withErrors($validator)
                 ->withInput();
        }else{
            try {
                // print_r($request->all());die;
                $update=Transaction::findOrFail($id);
                $update->transaction_date=$request->date;
                $update->expense_category_id=$request->expense_category_id;
                $update->payment_mode=$request->payment_mode;
                $update->description=$request->description;
                $update->amount=$request->amount;
                $update->type='expense';
                $update->created_by = Auth::user()->id;
                $update->save();
                if($update){
                    return redirect('manage-expense')->with('success','Successfully Submitted');
                }
            } catch (\Throwable $th) {
                return $th->getMessage();
            }

        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $delete = Transaction::find($id);
        $delete->delete();
    }
    function expense_report(){
        return view('expense-report');
    }
    function fetchExpenseReport(Request $request){
        $user_id=Auth::user()->id;
        $result = array('data' => array());
        $report=Transaction::select('transaction.*','users.name as user_name','expense_category.name as cat_name')
                            ->leftjoin('users','users.id','=','transaction.created_by')
                            ->leftjoin('expense_category','expense_category.id','=','transaction.expense_category_id')->where('transaction.type','=','expense')->latest();;


        if(!empty($request->datefrom)){
         $datefrom=date('Y-m-d',strtotime($request->datefrom));

         $report->whereDate('transaction.transaction_date', '>=', $datefrom);

        }
        if (!empty($request->dateto)) {
            $dateto=date('Y-m-d',strtotime($request->dateto));
            $report->whereDate('transaction.transaction_date', '<=', $dateto);
        }
        
        

        $data=$report->get();

         $i=1;
         foreach ($data as $key => $value) {
            
            $button='';
        
            $result['data'][$key] = array(
                $i,
                $value['transaction_date'],
                $value['cat_name'],
                $value['payment_mode'],
                $value['description'],
                $value['amount'],
                $value['user_name'],
               
            );
       $i++;  }
     echo json_encode($result);
    }
  
}
