<?php

namespace App\Http\Controllers;

use App\Models\Medicine;
use App\Models\Sale;
use App\Models\SaleDetail;
use App\Models\Shift;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class PosController extends Controller
{
    public function index()
    {
        $activeShift = Shift::where('user_id', auth()->id())
            ->whereNull('end_time')
            ->first();

        if (!$activeShift) {
            return redirect()->route('shift.check');
        }

        return view('transactions.pos.index', compact('activeShift'));
    }

    public function searchMedicines(Request $request)
    {
        $query = $request->get('q');
        if (!$query) return response()->json([]);

        $medicines = Medicine::with('unit')
            ->where('name', 'like', "%{$query}%")
            ->orWhere('code', 'like', "%{$query}%")
            ->limit(20)
            ->get();
            
        return response()->json($medicines);
    }

    public function storeTransaction(Request $request)
    {
        $activeShift = Shift::where('user_id', auth()->id())
            ->whereNull('end_time')
            ->first();

        if (!$activeShift) {
            return response()->json(['success' => false, 'message' => 'Tidak ada shift aktif'], 400);
        }

        try {
            DB::beginTransaction();

            $total = 0;
            $items = $request->items; // array of {medicine_id, qty, price, subtotal}

            $totalQty = 0;
            foreach($items as $item) {
                $total += $item['subtotal'];
                $totalQty += $item['qty'];
            }

            $sale = Sale::create([
                'invoice_number' => 'INV-' . strtoupper(uniqid()),
                'user_id' => auth()->id(),
                'shift_id' => $activeShift->id,
                'date' => Carbon::now()->toDateString(),
                'total_qty' => $totalQty,
                'total_amount' => $total,
                'paid_amount' => $request->amount_paid,
                'change_amount' => $request->change_amount,
                'status' => 'completed',
            ]);

            foreach($items as $item) {
                SaleDetail::create([
                    'sale_id' => $sale->id,
                    'medicine_id' => $item['medicine_id'],
                    'qty' => $item['qty'],
                    'price' => $item['price'],
                    'subtotal' => $item['subtotal']
                ]);

                // Reduce stock
                Medicine::find($item['medicine_id'])->decrement('current_stock', $item['qty']);
            }

            DB::commit();

            return response()->json([
                'success' => true, 
                'sale_id' => $sale->id,
                'message' => 'Transaksi berhasil'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()], 500);
        }
    }

    public function printReceipt($id)
    {
        $sale = Sale::with(['details.medicine.unit', 'user'])->findOrFail($id);
        return view('transactions.pos.receipt', compact('sale'));
    }
}
