<?php

namespace App\Http\Controllers\Accounting;

use App\Exports\TransactionExport;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AccountTransaction;
use App\Models\Company;
use App\Models\User;
use App\Models\VoucherType;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class AccountTransactionsController extends Controller
{
    function __construct()
    {
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
        $data = AccountTransaction::with(
                'Account',
                'VoucherType',
                'CreditTransaction',
                'DebitTransaction',
                'contraVoucher',
                'paymentVoucher',
                'journalVoucher',
                'receiptVoucher',
                'OpdVoucher',
                'IPDAdmissionVoucher',
                'pathologyVoucher',
                'SalesVoucher'
        );
            // ->where('transaction_type','DEBIT');

        if ($request->ajax()) {
            $sort_by      = $request->get('sort_by') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');
            $start_date   = $request->get('start_date');
            $end_date     = $request->get('end_date');
            $voucher_type = $request->get('voucher_type');
            $from_date       = $request->start_date?Carbon::createFromFormat($this->companyDateFormate(), $request->start_date)->format('Y-m-d'):'';
            $to_date         = $request->end_date?Carbon::createFromFormat($this->companyDateFormate(), $request->end_date)->format('Y-m-d'):'';

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->whereHas('Account', function ($accountQuery) use ($search_query) {
                    $accountQuery->where('accounts.name', 'like', '%' . $search_query . '%');
                })->orWhere('transactions_no', 'like', '%' . $search_query . '%');
            })
            ->when($from_date != '' && $to_date != '', function($query) use($from_date, $to_date) {
                $query->whereBetween('transaction_date', [
                    date('Y-m-d', strtotime($from_date)),
                    date('Y-m-d', strtotime($to_date))
                ]);
            })
            ->when(!empty($voucher_type), function ($query) use ($voucher_type) {
                return $query->where('voucher_type', $voucher_type);
            })
            ->orderBy('id','desc')
            // ->groupBy('transactions_no')
            ->paginate($sort_by);

            return view('account-transactions.table', compact('data'));
        }
        else
        {
            $voucher_types = VoucherType::where('status','1')->select(['name','code'])->get();
            $data          = $data->orderBy('id','desc')
            // ->groupBy('transactions_no')
            ->paginate(10);

            return view('account-transactions.index',compact('data','voucher_types','companyDateFormate'));
        }
    }

    /**
     * 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)
    {
        //
    }

    /**
     * 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)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function statement(Request $request)
    {
       
        $company = Company::find(Auth::user()->company_id);
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

        if ($request->ajax()) {
            $from_date       = $request->from_date?Carbon::createFromFormat($this->companyDateFormate(), $request->from_date)->format('Y-m-d'):date('Y-m-d');
            $to_date         = $request->to_date?Carbon::createFromFormat($this->companyDateFormate(), $request->to_date)->format('Y-m-d'):date('Y-m-d');
            $data = $this->queryFilter($request);
            return view('invoice-formats.transactions.statement-table', compact('data','from_date','to_date','company'));
        }
        else
        {
            $voucher_type = VoucherType::where('code', 'JOURNAL')->where(['status' => 1])->first();
            return view('invoice-formats.transactions.statement',compact('companyDateFormate'));
        }
    }
    public function exportStatement(Request $request)
    {
        $data = $this->queryFilter($request);
        return Excel::download(new TransactionExport($data->toArray()), 'transaction-statements.xlsx');
    }

    public function queryFilter(Request $request)
    {
        $from_date       = $request->from_date?Carbon::createFromFormat($this->companyDateFormate(), $request->from_date)->format('Y-m-d'):date('Y-m-d');
        $to_date         = $request->to_date?Carbon::createFromFormat($this->companyDateFormate(), $request->to_date)->format('Y-m-d'):date('Y-m-d');
        $branch          = $request->branch ?? '';
        $account         = $request->account ?? '';
        $created_by      = $request->created_by??'';
        $voucher_type_search    = $request->voucher_type??'';
        $payment_mode    = $request->payment_mode??'';
        $data = AccountTransaction::with(
            'Account',
            'VoucherType',
            'CreditTransaction',
            'DebitTransaction',
            'contraVoucher',
            'paymentVoucher',
            'journalVoucher',
            'receiptVoucher',
            'OpdVoucher',
            'IPDAdmissionVoucher',
            'pathologyVoucher',
            'SalesVoucher'
    );
        $data = $data->when(!empty($account), function ($query) use ($account) {
            return $query->whereHas('Account', function ($accountQuery) use ($account) {
                $accountQuery->where('accounts.id',$account);
            });
            // ->orWhere('transactions_no', 'like', '%' . $account . '%');
        })
        ->when($from_date != '' && $to_date != '', function($query) use($from_date, $to_date) {
            $query->whereBetween('transaction_date', [
                date('Y-m-d', strtotime($from_date)),
                date('Y-m-d', strtotime($to_date))
            ]);
        })
        ->when($voucher_type_search != '', function($query) use($voucher_type_search) {
                $query->where('voucher_type', $voucher_type_search);
        })
        ->when($payment_mode != '', function($query) use($payment_mode) {
            $query->whereHas('receiptVoucher.accountReceiptDetail', function ($query) use ($payment_mode) {
                $query->where('ac_receipt_details.transaction_mode_id', $payment_mode);
            });
        })
        ->when($branch != '', function($query) use($branch) {
            $query->where('company_id', $branch);
        })
        ->when($created_by != '', function($query) use($created_by) {
            $query->where('created_by', $created_by);
        })
        ->orderBy('id','desc')->get();
        return $data;
    }
}
