<?php

namespace App\Exports;

use App\Models\Rolepengeluaran;
use App\Models\Transaksi;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromView;

class KeuanganExport implements FromView
{
    protected $tgl1;
    protected $tgl2;

    function __construct($tgl1, $tgl2)
    {
        $this->tgl1 = $tgl1;
        $this->tgl2 = $tgl2;
    }
    public function view(): View
    {
        $data = [
            'tgl1' => 'DARI TANGGAL ' . date('d-m-Y', strtotime($this->tgl1)),
            'tgl2' => 'SAMPAI TANGGAL ' . date('d-m-Y', strtotime($this->tgl2)),
        ];

        $penjualan = Transaksi::where(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"), '>=',  $this->tgl1)
            ->where(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"), '<=',  $this->tgl2)
            ->selectRaw("SUM(IF(via_bayar ='T', total - ongkir,0)) as jmlt, SUM(IF(via_bayar ='K', total - ongkir,0)) as jmlk, DATE_FORMAT(created_at, '%Y-%m-%d') as tgl, SUM(ongkir) as ok ")
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
            ->where('sts_transaksi', 'N')
            ->get();

        $pengeluaran = Rolepengeluaran::where(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"), '>=',  $this->tgl1)
            ->where(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"), '<=',  $this->tgl2)
            ->selectRaw("SUM(total) as jml, DATE_FORMAT(created_at, '%Y-%m-%d') as tgl ")
            ->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
            ->get();


        return view('admin.laporan.export_keuangan', [
            'penjualan' => $penjualan,
            'pengeluaran' => $pengeluaran,
            'no' => 1,
            'data' =>  $data,
        ]);
    }
}
