<?php

namespace App\Http\Controllers;

use App\DataTables\TransactionDataTable;
use Illuminate\Http\Request;
use App\Exports\TransactionExport;
use Carbon\Carbon;
use App\Models\Transaction;
use App\Models\Office;
use Maatwebsite\Excel\Facades\Excel;


class TransactionController extends Controller
{
    public function index()
    {
         $from = Carbon::parse(sprintf(
            '%s 00:00',
            request()->query('from', Carbon::now()->toDateString())
        ));
        $to = Carbon::parse(sprintf(
            '%s 23:59:59',
            request()->query('to', Carbon::now()->toDateString())
        ));
            $qb = Transaction::with('account')->whereBetween('created_at', [$from, $to]);
               
        if(request()->query('office_id')){
            $qb->whereHas('account',function($query){
               $query->where('office_id',request()->query('office_id'));
            });
        }
        $transactions=$qb->paginate(20);
   
        
        return view('transactions.index',compact('transactions'));
    }
    
      public function export() 
    {
        $office = Office::find(request()->query('office_id'));
        $name = $office?$office->name:auth()->user()->name;
        $name .= '-'.request()->query('from').'-'.request()->query('to');
        return Excel::download(new TransactionExport, $name.'.xlsx');
    }
}
