<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Sale;
use App\Models\Purchase;
use App\Models\PurchaseItem;
use App\Models\Material;
use App\Models\Sparepart;
use App\Models\Product;
use App\Models\Production;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Barryvdh\DomPDF\Facade\Pdf;

class ReportController extends Controller
{
    /**
     * Laporan Penjualan
     */
    public function sales(Request $request)
    {
        $query = Sale::with(['product', 'user', 'order'])
            ->orderBy('sale_date', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('sale_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('sale_date', '<=', $request->end_date);
        }

        // Filter berdasarkan status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Search filter
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $query->where(function ($q) use ($searchTerm) {
                $q->whereHas('product', function($q2) use ($searchTerm) {
                    $q2->where('product_title', 'like', "%{$searchTerm}%");
                })
                ->orWhereHas('order', function($q2) use ($searchTerm) {
                    $q2->where('customer_name', 'like', "%{$searchTerm}%")
                       ->orWhere('customer_email', 'like', "%{$searchTerm}%");
                    if (is_numeric($searchTerm)) {
                        $q2->orWhere('id', $searchTerm);
                    }
                })
                ->orWhereHas('user', function($q2) use ($searchTerm) {
                    $q2->where('name', 'like', "%{$searchTerm}%");
                });
                if (is_numeric($searchTerm)) {
                    $q->orWhere('id', $searchTerm);
                }
            });
        }

        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $sales = $query->paginate($itemsPerPage)->withQueryString();
        
        // Statistik (hitung ulang setelah filter search)
        $statsQuery = Sale::with(['product', 'user', 'order'])
            ->orderBy('sale_date', 'desc');
        
        if ($request->filled('start_date')) {
            $statsQuery->where('sale_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $statsQuery->where('sale_date', '<=', $request->end_date);
        }
        if ($request->filled('status')) {
            $statsQuery->where('status', $request->status);
        }
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $statsQuery->where(function ($q) use ($searchTerm) {
                $q->whereHas('product', function($q2) use ($searchTerm) {
                    $q2->where('product_title', 'like', "%{$searchTerm}%");
                })
                ->orWhereHas('order', function($q2) use ($searchTerm) {
                    $q2->where('customer_name', 'like', "%{$searchTerm}%")
                       ->orWhere('customer_email', 'like', "%{$searchTerm}%");
                    if (is_numeric($searchTerm)) {
                        $q2->orWhere('id', $searchTerm);
                    }
                })
                ->orWhereHas('user', function($q2) use ($searchTerm) {
                    $q2->where('name', 'like', "%{$searchTerm}%");
                });
                if (is_numeric($searchTerm)) {
                    $q->orWhere('id', $searchTerm);
                }
            });
        }
        
        $totalSales = $statsQuery->sum('total_price');
        $totalQuantity = $statsQuery->sum('quantity');
        $totalTransactions = $statsQuery->count();

        // Chart data untuk 12 bulan terakhir
        $chartData = Sale::select(
                DB::raw('MONTH(sale_date) as month'),
                DB::raw('YEAR(sale_date) as year'),
                DB::raw('SUM(total_price) as total'),
                DB::raw('COUNT(*) as count')
            )
            ->where('sale_date', '>=', Carbon::now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        return view('admin.reports.sales', compact(
            'sales', 
            'totalSales', 
            'totalQuantity', 
            'totalTransactions',
            'chartData'
        ));
    }

    /**
     * Export Laporan Penjualan
     */
    public function salesExport(Request $request)
    {
        $query = Sale::with(['product', 'user', 'order'])
            ->orderBy('sale_date', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('sale_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('sale_date', '<=', $request->end_date);
        }

        // Filter berdasarkan status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $sales = $query->get();

        // Generate HTML table dengan styling untuk Excel
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: Arial, sans-serif;
            font-size: 11px;
        }
        th {
            background-color: #4472C4;
            color: #FFFFFF;
            font-weight: bold;
            text-align: center;
            padding: 10px 8px;
            border: 1px solid #000000;
            vertical-align: middle;
        }
        td {
            padding: 8px;
            border: 1px solid #CCCCCC;
            vertical-align: middle;
        }
        tr:nth-child(even) {
            background-color: #F2F2F2;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
        .text-left {
            text-align: left;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Tanggal</th>
                <th>Kode Order</th>
                <th>Nama Produk</th>
                <th>Customer</th>
                <th class="text-center">Quantity</th>
                <th class="text-right">Harga Satuan</th>
                <th class="text-right">Total Harga</th>
                <th class="text-center">Status</th>
                <th>Metode Pembayaran</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($sales as $index => $sale) {
            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td>' . htmlspecialchars($sale->sale_date->format('d/m/Y')) . '</td>';
            $html .= '<td class="text-center">' . htmlspecialchars($sale->order->id ?? '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($sale->product->product_title ?? '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($sale->user->name ?? $sale->order->customer_name ?? '-') . '</td>';
            $html .= '<td class="text-center">' . number_format($sale->quantity, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($sale->unit_price, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($sale->total_price, 0, ',', '.') . '</td>';
            $html .= '<td class="text-center">' . htmlspecialchars($sale->status_label ?? '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($sale->payment_method ?? '-') . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>
</body>
</html>';

        // Generate filename
        $filename = 'laporan_penjualan_' . now()->format('Y-m-d_H-i-s') . '.xls';

        // Return response dengan header untuk Excel
        return response($html, 200)
            ->header('Content-Type', 'application/vnd.ms-excel')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->header('Cache-Control', 'max-age=0');
    }

    /**
     * Export Laporan Penjualan ke PDF
     */
    public function salesPdf(Request $request)
    {
        $query = Sale::with(['product', 'user', 'order'])
            ->orderBy('sale_date', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('sale_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('sale_date', '<=', $request->end_date);
        }

        // Filter berdasarkan status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $sales = $query->get();
        
        // Statistik
        $totalSales = $sales->sum('total_price');
        $totalQuantity = $sales->sum('quantity');
        $totalTransactions = $sales->count();

        $pdf = Pdf::loadView('admin.reports.pdf.sales', compact(
            'sales', 
            'totalSales', 
            'totalQuantity', 
            'totalTransactions'
        ));

        $filename = 'laporan_penjualan_' . date('Y-m-d_H-i-s') . '.pdf';
        
        return $pdf->download($filename);
    }

    /**
     * Laporan Pembelian
     */
    public function purchases(Request $request)
    {
        $query = Purchase::with(['items'])
            ->orderBy('purchase_date', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('purchase_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('purchase_date', '<=', $request->end_date);
        }

        // Filter berdasarkan supplier - perbaiki dengan trim
        if ($request->filled('supplier') && trim($request->supplier) !== '') {
            $query->where('supplier_name', 'like', '%' . trim($request->supplier) . '%');
        }

        // Filter berdasarkan tipe pembelian
        if ($request->filled('purchase_type') && $request->purchase_type !== '') {
            $query->where('purchase_type', $request->purchase_type);
        }

        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $purchases = $query->paginate($itemsPerPage)->withQueryString();

        // Statistik (hitung ulang setelah filter)
        $statsQuery = Purchase::with(['items'])
            ->orderBy('purchase_date', 'desc');
        
        if ($request->filled('start_date')) {
            $statsQuery->where('purchase_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $statsQuery->where('purchase_date', '<=', $request->end_date);
        }
        if ($request->filled('supplier') && trim($request->supplier) !== '') {
            $statsQuery->where('supplier_name', 'like', '%' . trim($request->supplier) . '%');
        }
        if ($request->filled('purchase_type')) {
            $statsQuery->where('purchase_type', $request->purchase_type);
        }
        
        $totalAmount = $statsQuery->sum('total_amount');
        $totalTransactions = $statsQuery->count();

        // Detail items untuk chart
        $purchaseItems = PurchaseItem::with(['purchase'])
            ->whereHas('purchase', function($q) use ($request) {
                if ($request->filled('start_date')) {
                    $q->where('purchase_date', '>=', $request->start_date);
                }
                if ($request->filled('end_date')) {
                    $q->where('purchase_date', '<=', $request->end_date);
                }
            })
            ->get();

        $totalItems = $purchaseItems->sum('quantity');
        $totalItemValue = $purchaseItems->sum('total_price');

        // Chart data untuk 12 bulan terakhir
        $chartData = Purchase::select(
                DB::raw('MONTH(purchase_date) as month'),
                DB::raw('YEAR(purchase_date) as year'),
                DB::raw('SUM(total_amount) as total'),
                DB::raw('COUNT(*) as count')
            )
            ->where('purchase_date', '>=', Carbon::now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        return view('admin.reports.purchases', compact(
            'purchases',
            'totalAmount',
            'totalTransactions',
            'totalItems',
            'totalItemValue',
            'chartData'
        ));
    }

    /**
     * Export Laporan Pembelian
     */
    public function purchasesExport(Request $request)
    {
        $query = Purchase::with(['items'])
            ->orderBy('purchase_date', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('purchase_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('purchase_date', '<=', $request->end_date);
        }

        // Filter berdasarkan supplier
        if ($request->filled('supplier')) {
            $query->where('supplier_name', 'like', '%' . $request->supplier . '%');
        }

        // Filter berdasarkan tipe pembelian
        if ($request->filled('purchase_type')) {
            $query->where('purchase_type', $request->purchase_type);
        }

        $purchases = $query->get();

        // Generate HTML table dengan styling untuk Excel
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: Arial, sans-serif;
            font-size: 11px;
        }
        th {
            background-color: #4472C4;
            color: #FFFFFF;
            font-weight: bold;
            text-align: center;
            padding: 10px 8px;
            border: 1px solid #000000;
            vertical-align: middle;
        }
        td {
            padding: 8px;
            border: 1px solid #CCCCCC;
            vertical-align: middle;
        }
        tr:nth-child(even) {
            background-color: #F2F2F2;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Tanggal</th>
                <th>Kode Pembelian</th>
                <th>Supplier</th>
                <th class="text-center">Tipe</th>
                <th>Item Dibeli</th>
                <th class="text-right">Total Amount</th>
                <th>Catatan</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($purchases as $index => $purchase) {
            $itemsList = '';
            if ($purchase->items && $purchase->items->count() > 0) {
                $items = $purchase->items->take(5)->map(function($item) {
                    return ($item->item_name ?? '-') . ' (' . $item->quantity . ' ' . ($item->unit ?? 'pcs') . ')';
                })->implode(', ');
                if ($purchase->items->count() > 5) {
                    $items .= ' +' . ($purchase->items->count() - 5) . ' item lainnya';
                }
                $itemsList = $items;
            } else {
                $itemsList = '-';
            }

            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td>' . htmlspecialchars($purchase->purchase_date ? $purchase->purchase_date->format('d/m/Y') : '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($purchase->purchase_code) . '</td>';
            $html .= '<td>' . htmlspecialchars($purchase->supplier_name) . '</td>';
            $html .= '<td class="text-center">' . htmlspecialchars(ucfirst($purchase->purchase_type)) . '</td>';
            $html .= '<td>' . htmlspecialchars($itemsList) . '</td>';
            $html .= '<td class="text-right">' . number_format($purchase->total_amount, 0, ',', '.') . '</td>';
            $html .= '<td>' . htmlspecialchars(Str::limit($purchase->notes ?? '-', 50)) . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>
</body>
</html>';

        // Generate filename
        $filename = 'laporan_pembelian_' . now()->format('Y-m-d_H-i-s') . '.xls';

        // Return response dengan header untuk Excel
        return response($html, 200)
            ->header('Content-Type', 'application/vnd.ms-excel')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->header('Cache-Control', 'max-age=0');
    }

    /**
     * Export Laporan Pembelian ke PDF
     */
    public function purchasesPdf(Request $request)
    {
        $query = Purchase::with(['items'])
            ->orderBy('purchase_date', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('purchase_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('purchase_date', '<=', $request->end_date);
        }

        // Filter berdasarkan supplier
        if ($request->filled('supplier')) {
            $query->where('supplier_name', 'like', '%' . $request->supplier . '%');
        }

        // Filter berdasarkan tipe pembelian
        if ($request->filled('purchase_type')) {
            $query->where('purchase_type', $request->purchase_type);
        }

        $purchases = $query->get();

        // Statistik
        $totalAmount = $purchases->sum('total_amount');
        $totalTransactions = $purchases->count();

        // Detail items untuk statistik
        $purchaseItems = PurchaseItem::with(['purchase'])
            ->whereHas('purchase', function($q) use ($request) {
                if ($request->filled('start_date')) {
                    $q->where('purchase_date', '>=', $request->start_date);
                }
                if ($request->filled('end_date')) {
                    $q->where('purchase_date', '<=', $request->end_date);
                }
            })
            ->get();

        $totalItems = $purchaseItems->sum('quantity');

        $pdf = Pdf::loadView('admin.reports.pdf.purchases', compact(
            'purchases',
            'totalAmount',
            'totalTransactions',
            'totalItems'
        ));

        $filename = 'laporan_pembelian_' . date('Y-m-d_H-i-s') . '.pdf';
        
        return $pdf->download($filename);
    }

    /**
     * Laporan Barang Limit (Stock yang hampir habis)
     */
    public function stockLimit(Request $request)
    {
        // Query untuk materials dengan stock rendah
        $materialsBaseQuery = Material::where('is_active', true)
            ->where('stock', '<=', 10); // Threshold bisa disesuaikan

        if ($request->filled('category') && $request->category !== '') {
            $materialsBaseQuery->where('category', $request->category);
        }

        // Search filter untuk materials
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $materialsBaseQuery->where(function($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('material_code', 'like', "%{$searchTerm}%")
                  ->orWhere('description', 'like', "%{$searchTerm}%");
            });
        }

        // Pagination untuk materials
        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $materials = (clone $materialsBaseQuery)->orderBy('stock', 'asc')->paginate($itemsPerPage, ['*'], 'materials_page')->withQueryString();

        // Query untuk spareparts dengan stock rendah
        $sparepartsBaseQuery = Sparepart::where('is_active', true)
            ->where('stock', '<=', 5); // Threshold bisa disesuaikan

        if ($request->filled('brand') && $request->brand !== '') {
            $sparepartsBaseQuery->where('brand', $request->brand);
        }

        // Search filter untuk spareparts
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $sparepartsBaseQuery->where(function($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('part_code', 'like', "%{$searchTerm}%")
                  ->orWhere('part_number', 'like', "%{$searchTerm}%");
            });
        }

        // Pagination untuk spareparts
        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $spareparts = (clone $sparepartsBaseQuery)->orderBy('stock', 'asc')->paginate($itemsPerPage, ['*'], 'spareparts_page')->withQueryString();

        // Statistik (menggunakan query terpisah untuk akurasi - semua data, bukan hanya yang di-paginate)
        $totalMaterialsLow = (clone $materialsBaseQuery)->count();
        $totalSparepartsLow = (clone $sparepartsBaseQuery)->count();
        $totalLowStock = $totalMaterialsLow + $totalSparepartsLow;

        // Hitung nilai total stock rendah (menggunakan query terpisah untuk semua data)
        $materialsForStats = (clone $materialsBaseQuery)->get();
        $sparepartsForStats = (clone $sparepartsBaseQuery)->get();

        $totalValueMaterials = $materialsForStats->sum(function($item) {
            return $item->stock * $item->price;
        });

        $totalValueSpareparts = $sparepartsForStats->sum(function($item) {
            return $item->stock * $item->price;
        });

        $totalValueLowStock = $totalValueMaterials + $totalValueSpareparts;

        return view('admin.reports.stock-limit', compact(
            'materials',
            'spareparts',
            'totalMaterialsLow',
            'totalSparepartsLow',
            'totalLowStock',
            'totalValueMaterials',
            'totalValueSpareparts',
            'totalValueLowStock'
        ));
    }

    /**
     * Export Laporan Barang Limit
     */
    public function stockLimitExport(Request $request)
    {
        $materialsBaseQuery = Material::where('is_active', true)
            ->where('stock', '<=', 10);

        if ($request->filled('category')) {
            $materialsBaseQuery->where('category', $request->category);
        }

        $materials = $materialsBaseQuery->orderBy('stock', 'asc')->get();

        $sparepartsBaseQuery = Sparepart::where('is_active', true)
            ->where('stock', '<=', 5);

        if ($request->filled('brand')) {
            $sparepartsBaseQuery->where('brand', $request->brand);
        }

        $spareparts = $sparepartsBaseQuery->orderBy('stock', 'asc')->get();

        // Generate HTML table dengan styling untuk Excel
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: Arial, sans-serif;
            font-size: 11px;
        }
        th {
            background-color: #4472C4;
            color: #FFFFFF;
            font-weight: bold;
            text-align: center;
            padding: 10px 8px;
            border: 1px solid #000000;
            vertical-align: middle;
        }
        td {
            padding: 8px;
            border: 1px solid #CCCCCC;
            vertical-align: middle;
        }
        tr:nth-child(even) {
            background-color: #F2F2F2;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
    </style>
</head>
<body>
    <h2>Materials dengan Stock Rendah (≤ 10)</h2>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Kode</th>
                <th>Nama</th>
                <th class="text-center">Stock</th>
                <th>Unit</th>
                <th class="text-right">Harga</th>
                <th class="text-right">Total Value</th>
                <th>Kategori</th>
                <th class="text-center">Status</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($materials as $index => $material) {
            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td>' . htmlspecialchars($material->material_code) . '</td>';
            $html .= '<td>' . htmlspecialchars($material->name) . '</td>';
            $html .= '<td class="text-center">' . $material->stock . '</td>';
            $html .= '<td>' . htmlspecialchars($material->unit) . '</td>';
            $html .= '<td class="text-right">' . number_format($material->price, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($material->stock * $material->price, 0, ',', '.') . '</td>';
            $html .= '<td>' . htmlspecialchars($material->category) . '</td>';
            $html .= '<td class="text-center">' . ($material->stock <= 5 ? 'Kritis' : 'Rendah') . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>
    
    <br><br>
    
    <h2>Spareparts dengan Stock Rendah (≤ 5)</h2>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Kode</th>
                <th>Nama</th>
                <th class="text-center">Stock</th>
                <th>Unit</th>
                <th class="text-right">Harga</th>
                <th class="text-right">Total Value</th>
                <th>Brand</th>
                <th class="text-center">Status</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($spareparts as $index => $sparepart) {
            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->part_code) . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->name) . '</td>';
            $html .= '<td class="text-center">' . $sparepart->stock . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->unit) . '</td>';
            $html .= '<td class="text-right">' . number_format($sparepart->price, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($sparepart->stock * $sparepart->price, 0, ',', '.') . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->brand) . '</td>';
            $html .= '<td class="text-center">' . ($sparepart->stock <= 2 ? 'Kritis' : 'Rendah') . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>
</body>
</html>';

        // Generate filename
        $filename = 'laporan_barang_limit_' . now()->format('Y-m-d_H-i-s') . '.xls';

        // Return response dengan header untuk Excel
        return response($html, 200)
            ->header('Content-Type', 'application/vnd.ms-excel')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->header('Cache-Control', 'max-age=0');
    }

    /**
     * Laporan Barang Rusak
     */
    public function damagedItems(Request $request)
    {
        // Untuk sementara, kita akan menggunakan field 'is_active' = false sebagai indikator barang rusak
        // Atau bisa juga menggunakan tabel terpisah untuk tracking barang rusak
        
        $materialsBaseQuery = Material::hasDamage();
        $sparepartsBaseQuery = Sparepart::hasDamage();
        $productsQuery = Product::where('condition', 'damaged');

        // Filter berdasarkan kategori (untuk materials)
        if ($request->filled('category')) {
            $materialsBaseQuery->where('category', $request->category);
        }

        // Filter berdasarkan brand (untuk spareparts)
        if ($request->filled('brand')) {
            $sparepartsBaseQuery->where('brand', $request->brand);
        }

        // Search filter untuk materials
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $materialsBaseQuery->where(function($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('material_code', 'like', "%{$searchTerm}%");
            });
        }

        // Search filter untuk spareparts
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $sparepartsBaseQuery->where(function($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('part_code', 'like', "%{$searchTerm}%")
                  ->orWhere('part_number', 'like', "%{$searchTerm}%");
            });
        }

        // Pagination untuk materials
        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $materials = (clone $materialsBaseQuery)->orderBy('updated_at', 'desc')->paginate($itemsPerPage, ['*'], 'materials_page')->withQueryString();

        // Pagination untuk spareparts
        $spareparts = (clone $sparepartsBaseQuery)->orderBy('updated_at', 'desc')->paginate($itemsPerPage, ['*'], 'spareparts_page')->withQueryString();

        // Products tetap get() karena biasanya sedikit
        $products = $productsQuery->orderBy('updated_at', 'desc')->get();

        // Statistik (menggunakan query terpisah untuk akurasi - semua data, bukan hanya yang di-paginate)
        $totalDamagedMaterials = (clone $materialsBaseQuery)->count();
        $totalDamagedSpareparts = (clone $sparepartsBaseQuery)->count();
        $totalDamagedProducts = $products->count();
        $totalDamagedItems = $totalDamagedMaterials + $totalDamagedSpareparts + $totalDamagedProducts;

        // Hitung nilai total barang rusak (dari semua data, bukan hanya yang di-paginate)
        $allMaterials = (clone $materialsBaseQuery)->get();
        $allSpareparts = (clone $sparepartsBaseQuery)->get();

        $totalValueMaterials = $allMaterials->sum(function($item) {
            return ($item->damaged_stock ?? 0) * $item->price;
        });

        $totalValueSpareparts = $allSpareparts->sum(function($item) {
            return ($item->damaged_stock ?? 0) * $item->price;
        });

        $totalValueProducts = $products->sum(function($item) {
            return $item->product_prices;
        });

        $totalValueDamaged = $totalValueMaterials + $totalValueSpareparts + $totalValueProducts;

        return view('admin.reports.damaged-items', compact(
            'materials',
            'spareparts',
            'products',
            'totalDamagedMaterials',
            'totalDamagedSpareparts',
            'totalDamagedProducts',
            'totalDamagedItems',
            'totalValueMaterials',
            'totalValueSpareparts',
            'totalValueProducts',
            'totalValueDamaged'
        ));
    }

    /**
     * Export Laporan Barang Rusak
     */
    public function damagedItemsExport(Request $request)
    {
        $materialsQuery = Material::hasDamage();
        $sparepartsQuery = Sparepart::hasDamage();
        $productsQuery = Product::where('condition', 'damaged');

        // Filter berdasarkan kategori (untuk materials)
        if ($request->filled('category')) {
            $materialsQuery->where('category', $request->category);
        }

        // Filter berdasarkan brand (untuk spareparts)
        if ($request->filled('brand')) {
            $sparepartsQuery->where('brand', $request->brand);
        }

        $materials = $materialsQuery->orderBy('updated_at', 'desc')->get();
        $spareparts = $sparepartsQuery->orderBy('updated_at', 'desc')->get();
        $products = $productsQuery->orderBy('updated_at', 'desc')->get();

        // Generate HTML table dengan styling untuk Excel
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: Arial, sans-serif;
            font-size: 11px;
        }
        th {
            background-color: #4472C4;
            color: #FFFFFF;
            font-weight: bold;
            text-align: center;
            padding: 10px 8px;
            border: 1px solid #000000;
            vertical-align: middle;
        }
        td {
            padding: 8px;
            border: 1px solid #CCCCCC;
            vertical-align: middle;
        }
        tr:nth-child(even) {
            background-color: #F2F2F2;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
    </style>
</head>
<body>
    <h2>Materials Rusak</h2>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Kode</th>
                <th>Nama</th>
                <th class="text-center">Stock Total</th>
                <th class="text-center">Stock Rusak</th>
                <th class="text-center">Stock Baik</th>
                <th class="text-center">% Rusak</th>
                <th>Unit</th>
                <th class="text-right">Harga</th>
                <th class="text-right">Nilai Kerugian</th>
                <th>Kategori</th>
                <th>Tanggal Rusak</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($materials as $index => $material) {
            $damagedStock = $material->damaged_stock ?? 0;
            $goodStock = $material->good_stock ?? ($material->stock - $damagedStock);
            $damagePercentage = $material->stock > 0 ? ($damagedStock / $material->stock) * 100 : 0;

            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td>' . htmlspecialchars($material->material_code) . '</td>';
            $html .= '<td>' . htmlspecialchars($material->name) . '</td>';
            $html .= '<td class="text-center">' . $material->stock . '</td>';
            $html .= '<td class="text-center">' . $damagedStock . '</td>';
            $html .= '<td class="text-center">' . $goodStock . '</td>';
            $html .= '<td class="text-center">' . number_format($damagePercentage, 1) . '%</td>';
            $html .= '<td>' . htmlspecialchars($material->unit) . '</td>';
            $html .= '<td class="text-right">' . number_format($material->price, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($damagedStock * $material->price, 0, ',', '.') . '</td>';
            $html .= '<td>' . htmlspecialchars($material->category) . '</td>';
            $html .= '<td>' . ($material->damage_date ? $material->damage_date->format('d/m/Y') : '-') . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>
    
    <br><br>
    
    <h2>Spareparts Rusak</h2>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Kode</th>
                <th>Nama</th>
                <th class="text-center">Stock Total</th>
                <th class="text-center">Stock Rusak</th>
                <th class="text-center">Stock Baik</th>
                <th class="text-center">% Rusak</th>
                <th>Unit</th>
                <th class="text-right">Harga</th>
                <th class="text-right">Nilai Kerugian</th>
                <th>Brand</th>
                <th>Tanggal Rusak</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($spareparts as $index => $sparepart) {
            $damagedStock = $sparepart->damaged_stock ?? 0;
            $goodStock = $sparepart->good_stock ?? ($sparepart->stock - $damagedStock);
            $damagePercentage = $sparepart->stock > 0 ? ($damagedStock / $sparepart->stock) * 100 : 0;

            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->part_code) . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->name) . '</td>';
            $html .= '<td class="text-center">' . $sparepart->stock . '</td>';
            $html .= '<td class="text-center">' . $damagedStock . '</td>';
            $html .= '<td class="text-center">' . $goodStock . '</td>';
            $html .= '<td class="text-center">' . number_format($damagePercentage, 1) . '%</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->unit) . '</td>';
            $html .= '<td class="text-right">' . number_format($sparepart->price, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($damagedStock * $sparepart->price, 0, ',', '.') . '</td>';
            $html .= '<td>' . htmlspecialchars($sparepart->brand) . '</td>';
            $html .= '<td>' . ($sparepart->damage_date ? $sparepart->damage_date->format('d/m/Y') : '-') . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>';

        if ($products->count() > 0) {
            $html .= '<br><br>
    
    <h2>Products Rusak</h2>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>ID</th>
                <th>Nama</th>
                <th class="text-right">Harga</th>
                <th>Kategori</th>
                <th class="text-center">Kondisi</th>
                <th>Alasan Rusak</th>
                <th>Tanggal Rusak</th>
            </tr>
        </thead>
        <tbody>';

            foreach ($products as $index => $product) {
                $html .= '<tr>';
                $html .= '<td class="text-center">' . ($index + 1) . '</td>';
                $html .= '<td class="text-center">' . $product->id . '</td>';
                $html .= '<td>' . htmlspecialchars($product->product_title) . '</td>';
                $html .= '<td class="text-right">' . number_format($product->product_prices, 0, ',', '.') . '</td>';
                $html .= '<td>' . htmlspecialchars($product->category->name ?? '-') . '</td>';
                $html .= '<td class="text-center">' . htmlspecialchars(ucfirst($product->condition ?? 'damaged')) . '</td>';
                $html .= '<td>' . htmlspecialchars(Str::limit($product->damage_reason ?? '-', 50)) . '</td>';
                $html .= '<td>' . ($product->damage_date ? $product->damage_date->format('d/m/Y') : '-') . '</td>';
                $html .= '</tr>';
            }

            $html .= '</tbody>
    </table>';
        }

        $html .= '</body>
</html>';

        // Generate filename
        $filename = 'laporan_barang_rusak_' . now()->format('Y-m-d_H-i-s') . '.xls';

        // Return response dengan header untuk Excel
        return response($html, 200)
            ->header('Content-Type', 'application/vnd.ms-excel')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->header('Cache-Control', 'max-age=0');
    }

    /**
     * Export Laporan Barang Limit ke PDF
     */
    public function stockLimitPdf(Request $request)
    {
        // Ambil materials dengan stock rendah
        $materialsQuery = Material::where('is_active', true)
            ->where('stock', '<=', 10);

        if ($request->filled('category')) {
            $materialsQuery->where('category', $request->category);
        }

        $materials = $materialsQuery->orderBy('stock', 'asc')->get();

        // Ambil spareparts dengan stock rendah
        $sparepartsQuery = Sparepart::where('is_active', true)
            ->where('stock', '<=', 5);

        if ($request->filled('brand')) {
            $sparepartsQuery->where('brand', $request->brand);
        }

        $spareparts = $sparepartsQuery->orderBy('stock', 'asc')->get();

        // Statistik
        $totalMaterialsLow = $materials->count();
        $totalSparepartsLow = $spareparts->count();
        $totalLowStock = $totalMaterialsLow + $totalSparepartsLow;

        // Hitung nilai total stock rendah
        $totalValueMaterials = $materials->sum(function($item) {
            return $item->stock * $item->price;
        });

        $totalValueSpareparts = $spareparts->sum(function($item) {
            return $item->stock * $item->price;
        });

        $totalValueLowStock = $totalValueMaterials + $totalValueSpareparts;

        $pdf = Pdf::loadView('admin.reports.pdf.stock-limit', compact(
            'materials',
            'spareparts',
            'totalMaterialsLow',
            'totalSparepartsLow',
            'totalLowStock',
            'totalValueMaterials',
            'totalValueSpareparts',
            'totalValueLowStock'
        ));

        $filename = 'laporan_barang_limit_' . date('Y-m-d_H-i-s') . '.pdf';
        
        return $pdf->download($filename);
    }

    /**
     * Export Laporan Barang Rusak ke PDF
     */
    public function damagedItemsPdf(Request $request)
    {
        $materialsQuery = Material::hasDamage();
        $sparepartsQuery = Sparepart::hasDamage();
        $productsQuery = Product::where('condition', 'damaged');

        // Filter berdasarkan kategori (untuk materials)
        if ($request->filled('category')) {
            $materialsQuery->where('category', $request->category);
        }

        // Filter berdasarkan brand (untuk spareparts)
        if ($request->filled('brand')) {
            $sparepartsQuery->where('brand', $request->brand);
        }

        $materials = $materialsQuery->orderBy('updated_at', 'desc')->get();
        $spareparts = $sparepartsQuery->orderBy('updated_at', 'desc')->get();
        $products = $productsQuery->orderBy('updated_at', 'desc')->get();

        // Statistik
        $totalDamagedMaterials = $materials->count();
        $totalDamagedSpareparts = $spareparts->count();
        $totalDamagedProducts = $products->count();
        $totalDamagedItems = $totalDamagedMaterials + $totalDamagedSpareparts + $totalDamagedProducts;

        // Hitung nilai total barang rusak
        $totalValueMaterials = $materials->sum(function($item) {
            return $item->stock * $item->price;
        });

        $totalValueSpareparts = $spareparts->sum(function($item) {
            return $item->stock * $item->price;
        });

        $totalValueProducts = $products->sum(function($item) {
            return $item->product_prices;
        });

        $totalValueDamaged = $totalValueMaterials + $totalValueSpareparts + $totalValueProducts;

        $pdf = Pdf::loadView('admin.reports.pdf.damaged-items', compact(
            'materials',
            'spareparts',
            'products',
            'totalDamagedMaterials',
            'totalDamagedSpareparts',
            'totalDamagedProducts',
            'totalDamagedItems',
            'totalValueMaterials',
            'totalValueSpareparts',
            'totalValueProducts',
            'totalValueDamaged'
        ));

        $filename = 'laporan_barang_rusak_' . date('Y-m-d_H-i-s') . '.pdf';
        
        return $pdf->download($filename);
    }

    /**
     * Laporan Produksi
     */
    public function productions(Request $request)
    {
        $query = Production::with([
            'order', 
            'product', 
            'teknisi', 
            'productionMaterials.material',
            'productionSpareparts.sparepart',
            'supervisor',
            'completionApprover',
            'materialsReceiver'
        ])->orderBy('created_at', 'desc');

        // Filter berdasarkan tanggal
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

        // Filter berdasarkan status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter berdasarkan teknisi
        if ($request->filled('teknisi_id')) {
            $query->where('teknisi_id', $request->teknisi_id);
        }

        // Filter berdasarkan product
        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        // Search filter
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $query->where(function ($q) use ($searchTerm) {
                $q->whereHas('order', function($q2) use ($searchTerm) {
                    $q2->where('customer_name', 'like', "%{$searchTerm}%")
                       ->orWhere('customer_email', 'like', "%{$searchTerm}%");
                    if (is_numeric($searchTerm)) {
                        $q2->orWhere('id', $searchTerm);
                    }
                })
                ->orWhereHas('product', function($q2) use ($searchTerm) {
                    $q2->where('product_title', 'like', "%{$searchTerm}%");
                })
                ->orWhereHas('teknisi', function($q2) use ($searchTerm) {
                    $q2->where('name', 'like', "%{$searchTerm}%");
                });
                if (is_numeric($searchTerm)) {
                    $q->orWhere('id', $searchTerm);
                }
            });
        }

        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $productions = $query->paginate($itemsPerPage)->withQueryString();

        // Statistik (hitung ulang setelah filter search)
        $statsQuery = Production::with([
            'order', 
            'product', 
            'teknisi', 
            'productionMaterials.material',
            'productionSpareparts.sparepart',
            'supervisor',
            'completionApprover',
            'materialsReceiver'
        ])->orderBy('created_at', 'desc');
        
        if ($request->filled('start_date')) {
            $statsQuery->where('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $statsQuery->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }
        if ($request->filled('status')) {
            $statsQuery->where('status', $request->status);
        }
        if ($request->filled('teknisi_id')) {
            $statsQuery->where('teknisi_id', $request->teknisi_id);
        }
        if ($request->filled('product_id')) {
            $statsQuery->where('product_id', $request->product_id);
        }
        if ($request->filled('search') && trim($request->search) !== '') {
            $searchTerm = trim($request->search);
            $statsQuery->where(function ($q) use ($searchTerm) {
                $q->whereHas('order', function($q2) use ($searchTerm) {
                    $q2->where('customer_name', 'like', "%{$searchTerm}%")
                       ->orWhere('customer_email', 'like', "%{$searchTerm}%");
                    if (is_numeric($searchTerm)) {
                        $q2->orWhere('id', $searchTerm);
                    }
                })
                ->orWhereHas('product', function($q2) use ($searchTerm) {
                    $q2->where('product_title', 'like', "%{$searchTerm}%");
                })
                ->orWhereHas('teknisi', function($q2) use ($searchTerm) {
                    $q2->where('name', 'like', "%{$searchTerm}%");
                });
                if (is_numeric($searchTerm)) {
                    $q->orWhere('id', $searchTerm);
                }
            });
        }
        
        $totalProductions = $statsQuery->count();
        $totalMaterialCost = $statsQuery->sum('total_material_cost') ?? 0;
        $totalSparepartCost = $statsQuery->sum('total_sparepart_cost') ?? 0;
        $totalLaborCost = $statsQuery->sum('labor_cost') ?? 0;
        $totalProductionCost = $totalMaterialCost + $totalSparepartCost + $totalLaborCost;

        // Teknisi list untuk filter
        $teknisiList = \App\Models\User::where('user_type', 'teknisi')->get();
        $productList = Product::where('is_active', true)->get();

        // Chart data untuk 12 bulan terakhir
        $chartData = Production::select(
                DB::raw('MONTH(created_at) as month'),
                DB::raw('YEAR(created_at) as year'),
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(total_production_cost) as total_cost'),
                DB::raw('SUM(labor_cost) as total_labor')
            )
            ->where('created_at', '>=', Carbon::now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        return view('admin.reports.productions', compact(
            'productions',
            'totalProductions',
            'totalMaterialCost',
            'totalSparepartCost',
            'totalLaborCost',
            'totalProductionCost',
            'teknisiList',
            'productList',
            'chartData'
        ));
    }

    /**
     * Export Laporan Produksi
     */
    public function productionsExport(Request $request)
    {
        $query = Production::with([
            'order', 
            'product', 
            'teknisi', 
            'productionMaterials.material',
            'productionSpareparts.sparepart'
        ])->orderBy('created_at', 'desc');

        // Filter sama seperti index
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('teknisi_id')) {
            $query->where('teknisi_id', $request->teknisi_id);
        }
        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        $productions = $query->get();

        // Generate HTML table dengan styling untuk Excel
        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            font-family: Arial, sans-serif;
            font-size: 11px;
        }
        th {
            background-color: #4472C4;
            color: #FFFFFF;
            font-weight: bold;
            text-align: center;
            padding: 10px 8px;
            border: 1px solid #000000;
            vertical-align: middle;
        }
        td {
            padding: 8px;
            border: 1px solid #CCCCCC;
            vertical-align: middle;
        }
        tr:nth-child(even) {
            background-color: #F2F2F2;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>ID</th>
                <th>Order ID</th>
                <th>Customer</th>
                <th>Produk</th>
                <th class="text-center">Qty</th>
                <th>Teknisi</th>
                <th>Tanggal Mulai</th>
                <th>Durasi</th>
                <th class="text-center">Status</th>
                <th class="text-right">Biaya Bahan</th>
                <th class="text-right">Biaya Sparepart</th>
                <th class="text-right">Labor Cost</th>
                <th class="text-right">Total Biaya</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($productions as $index => $production) {
            $duration = '-';
            if ($production->start_date && $production->end_date) {
                $duration = $production->start_date->diffInDays($production->end_date) . ' hari';
            } elseif ($production->estimated_duration_days) {
                $duration = 'Estimasi: ' . $production->estimated_duration_days . ' hari';
            }

            $html .= '<tr>';
            $html .= '<td class="text-center">' . ($index + 1) . '</td>';
            $html .= '<td class="text-center">' . $production->id . '</td>';
            $html .= '<td class="text-center">' . ($production->order->id ?? '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($production->order->customer_name ?? '-') . '</td>';
            $html .= '<td>' . htmlspecialchars($production->product->product_title ?? '-') . '</td>';
            $html .= '<td class="text-center">' . $production->quantity . '</td>';
            $html .= '<td>' . htmlspecialchars($production->teknisi->name ?? '-') . '</td>';
            $html .= '<td>' . ($production->actual_start_date ? $production->actual_start_date->format('d/m/Y') : ($production->start_date ? $production->start_date->format('d/m/Y') : '-')) . '</td>';
            $html .= '<td class="text-center">' . $duration . '</td>';
            $html .= '<td class="text-center">' . htmlspecialchars(ucfirst(str_replace('_', ' ', $production->status))) . '</td>';
            $html .= '<td class="text-right">' . number_format($production->total_material_cost ?? 0, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($production->total_sparepart_cost ?? 0, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($production->labor_cost ?? 0, 0, ',', '.') . '</td>';
            $html .= '<td class="text-right">' . number_format($production->total_actual_cost ?? 0, 0, ',', '.') . '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>
    </table>
</body>
</html>';

        // Generate filename
        $filename = 'laporan_produksi_' . now()->format('Y-m-d_H-i-s') . '.xls';

        // Return response dengan header untuk Excel
        return response($html, 200)
            ->header('Content-Type', 'application/vnd.ms-excel')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->header('Cache-Control', 'max-age=0');
    }

    /**
     * Export Laporan Produksi ke PDF
     */
    public function productionsPdf(Request $request)
    {
        $query = Production::with([
            'order', 
            'product', 
            'teknisi', 
            'productionMaterials.material',
            'productionSpareparts.sparepart'
        ])->orderBy('created_at', 'desc');

        // Filter sama seperti index
        if ($request->filled('start_date')) {
            $query->where('created_at', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('teknisi_id')) {
            $query->where('teknisi_id', $request->teknisi_id);
        }
        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        $productions = $query->get();

        // Statistik
        $totalProductions = $productions->count();
        $totalMaterialCost = $productions->sum('total_material_cost') ?? 0;
        $totalSparepartCost = $productions->sum('total_sparepart_cost') ?? 0;
        $totalLaborCost = $productions->sum('labor_cost') ?? 0;
        $totalProductionCost = $totalMaterialCost + $totalSparepartCost + $totalLaborCost;

        $pdf = Pdf::loadView('admin.reports.pdf.productions', compact(
            'productions',
            'totalProductions',
            'totalMaterialCost',
            'totalSparepartCost',
            'totalLaborCost',
            'totalProductionCost'
        ));

        $filename = 'laporan_produksi_' . date('Y-m-d_H-i-s') . '.pdf';
        
        return $pdf->download($filename);
    }
}
