<?php

namespace App\Http\Controllers;

use App\Models\PtPurchase;
use App\Models\Member;
use App\Models\Visitor;
use App\Models\Product;
use App\Models\Instruktur;
use Illuminate\Http\Request;

class PtPurchaseController extends Controller
{
    public function index(Request $request)
    {
        // Ambil bulan dan tahun dari filter, default bulan berjalan
        $bulan = $request->input('bulan', date('m'));
        $tahun = $request->input('tahun', date('Y'));
        $tanggal_awal = $request->input('tanggal_awal');
        $tanggal_akhir = $request->input('tanggal_akhir');
        $search = $request->input('search');
    
        $query = PtPurchase::with(['member', 'visitor', 'product', 'instruktur']);
    
        // Filter tanggal (rentang)
        if ($tanggal_awal && $tanggal_akhir) {
            $query->whereBetween('tanggal', [$tanggal_awal, $tanggal_akhir]);
        } else {
            // Filter default: bulan berjalan
            $query->whereMonth('tanggal', $bulan)->whereYear('tanggal', $tahun);
        }
    
        // Filter search (nama member/visitor)
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->whereHas('member', function($q2) use ($search) {
                    $q2->where('nama', 'like', "%$search%");
                })->orWhereHas('visitor', function($q3) use ($search) {
                    $q3->where('nama', 'like', "%$search%");
                });
            });
        }
    
        $purchases = $query->orderBy('tanggal', 'desc')->paginate(15);
    
        // Hitung total transaksi (harga) sesuai filter
        $total = (clone $query)->sum('harga');
    
        return view('pt_purchases.index', compact(
            'purchases', 'bulan', 'tahun', 'tanggal_awal', 'tanggal_akhir', 'search', 'total'
        ));
    }

    public function create()
    {
        $products = Product::whereIn('kategori', ['pt_sesi', 'pt_visit'])->get();
        $members = Member::select('id', 'nama', 'alamat')->get();
        $visitors = Visitor::select('id', 'nama', 'alamat')->get();
        $instrukturs = Instruktur::select('id', 'nama')->get();
        return view('pt_purchases.create', compact('products', 'members', 'visitors', 'instrukturs'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'buyer_type'      => 'required|in:member,visitor',
            'buyer_id'        => 'required|integer',
            'produk_id'       => 'required|exists:products,id',
            'instruktur_id'   => 'required|exists:instrukturs,id',
            'tanggal'         => 'required|date',
            'harga'           => 'required|integer|min:0',
            'payment_method'  => 'required|in:cash,QRIS',
            'bayar' => 'required|integer|min:0',
            'kembalian' => 'required|integer|min:0',
        ]);
    
        $ptPurchase = PtPurchase::create([
            'member_id'    => $request->buyer_type === 'member' ? $request->buyer_id : null,
            'visitor_id'   => $request->buyer_type === 'visitor' ? $request->buyer_id : null,
            'produk_id'    => $request->produk_id,
            'instruktur_id'=> $request->instruktur_id,
            'tanggal'      => $request->tanggal,
            'harga'        => $request->harga,
            'payment_method'=> $request->payment_method,
            'bayar' => $request->bayar,
            'kembalian' => $request->kembalian,
        ]);
    
        return redirect()->route('pt_purchases.print', $ptPurchase->id);
    }

    public function print($id)
    {
        $trx = PtPurchase::with(['member', 'visitor', 'product', 'instruktur'])->findOrFail($id);
        return view('pt_purchases.print', compact('trx'));
    }
    
    public function destroy(PtPurchase $pt_purchase)
    {
        if (auth()->user()->role !== 'admin') {
            abort(403, 'Unauthorized action.');
        } 
        $pt_purchase->delete();
        return redirect()->route('pt_purchases.index')->with('success', 'Transaksi PT berhasil dihapus!');
    }

}