<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class PendapatanController extends Controller
{
    
    public function index()
    {
        
        $pendapatan = DB::table('orders')
            ->join('products', 'orders.product_id', '=', 'products.id')
            ->where('orders.status', 'done') // atau 'selesai' sesuai tabel kamu
            ->select(
                'products.name as nama_produk',
                DB::raw('SUM(orders.quantity) as total_jumlah'),
                'products.price as harga_satuan',
                DB::raw('SUM(orders.total_price) as total_pendapatan')
            )
            ->groupBy('products.id', 'products.name', 'products.price')
            ->get();

        
        $totalPendapatan = DB::table('orders')
            ->where('status', 'done')
            ->sum('total_price');

        return view('admin.pendapatan.index', compact(
            'pendapatan',
            'totalPendapatan'
        ));
    }

   
    public function exportPendapatanExcel()
    {
        $pendapatan = DB::table('orders')
            ->join('products', 'orders.product_id', '=', 'products.id')
            ->where('orders.status', 'done')
            ->select(
                'products.name as nama_produk',
                DB::raw('SUM(orders.quantity) as total_jumlah'),
                'products.price as harga_satuan',
                DB::raw('SUM(orders.total_price) as total_pendapatan')
            )
            ->groupBy('products.id', 'products.name', 'products.price')
            ->get();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        
        $sheet->setCellValue('A1', 'No');
        $sheet->setCellValue('B1', 'Nama Produk');
        $sheet->setCellValue('C1', 'Jumlah Terjual');
        $sheet->setCellValue('D1', 'Harga Satuan');
        $sheet->setCellValue('E1', 'Total Pendapatan');

        $row = 2;
        $no  = 1;

        foreach ($pendapatan as $p) {
            $sheet->setCellValue('A'.$row, $no++);
            $sheet->setCellValue('B'.$row, $p->nama_produk);
            $sheet->setCellValue('C'.$row, $p->total_jumlah);
            $sheet->setCellValue('D'.$row, $p->harga_satuan);
            $sheet->setCellValue('E'.$row, $p->total_pendapatan);
            $row++;
        }

        $writer = new Xlsx($spreadsheet);
        $fileName = 'laporan_pendapatan.xlsx';

        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="'.$fileName.'"');

        $writer->save('php://output');
        exit;
    }
}

