<?php

namespace App\Http\Controllers;

use App\Models\Sale;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;

class SaleController extends Controller
{
    /**
     * Display a listing of the sales.
     * 
     * Data Sale (Penjualan) dibuat otomatis dari:
     * 1. Order dengan status pembayaran 'selesai'
     * 2. Production dengan status 'selesai'
     * 
     * Admin hanya bisa melihat dan detail, tidak bisa create/edit/delete
     */
    public function index(Request $request)
    {
        $query = Sale::with(['order', 'product', 'user']);

        // Jika ada pencarian - perbaiki dengan grouping yang benar
        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 ($q3) use ($searchTerm) {
                    $q3->where('customer_name', 'like', '%' . $searchTerm . '%')
                        ->orWhere('customer_email', 'like', '%' . $searchTerm . '%')
                        ->orWhere('id', 'like', '%' . $searchTerm . '%');
                })
                ->orWhere('payment_method', 'like', '%' . $searchTerm . '%')
                ->orWhere('status', 'like', '%' . $searchTerm . '%')
                ->orWhere('id', 'like', '%' . $searchTerm . '%');
            });
        }

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

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

        // Filter berdasarkan tanggal
        if ($request->filled('date_from')) {
            $query->whereDate('sale_date', '>=', $request->date_from);
        }

        if ($request->filled('date_to')) {
            $query->whereDate('sale_date', '<=', $request->date_to);
        }

        // Urutkan terbaru & pagination
        $sales = $query->latest()->paginate(10)->withQueryString();

        return view('admin.transaksi.sales.index', compact('sales'));
    }

    /**
     * Display the specified sale.
     * 
     * Menampilkan detail penjualan yang sudah dibuat otomatis
     */
    public function show(Sale $sale)
    {
        $sale->load(['order', 'product', 'user']);

        return view('admin.transaksi.sales.show', compact('sale'));
    }
}