<?php

namespace App\Http\Controllers;

use App\Models\PosSale;
use App\Services\AffiliateService;
use Illuminate\Http\Request;

class PosSaleController extends Controller
{
    public function index()
    {
        $userId = request()->query('user_id');
        if (!$userId) {
            return response()->json(['message' => 'User ID required'], 400);
        }
        return response()->json(PosSale::where('user_id', $userId)->with(['customer', 'product', 'channel', 'payment', 'admin'])->get());
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'pos_customer_id' => 'required|integer',
            'pos_product_id' => 'required|integer',
            'pos_channel_id' => 'required|integer',
            'pos_payment_id' => 'required|integer',
            'pos_admin_id' => 'required|integer',
            'price' => 'required|numeric',
            'link' => 'nullable|string',
            'date' => 'required|date',
            'ship_date' => 'nullable|date',
            'note' => 'nullable|string',
            'referral_code' => 'nullable|string',
            'user_id' => 'required|integer',
        ]);

        $posSale = PosSale::create($validated);

        // Handle affiliate commission if referral code is provided
        if ($validated['referral_code']) {
            \App\Services\AffiliateService::processCommission(
                $validated['referral_code'], 
                $validated['price']
            );
        }

        return response()->json($posSale->load(['customer', 'product', 'channel', 'payment', 'admin']), 201);
    }

    public function show($id)
    {
        $posSale = PosSale::findOrFail($id);

        return response()->json($posSale->load(['customer', 'product', 'channel', 'payment', 'admin']));
    }

    public function update(Request $request, $id)
    {
        $posSale = PosSale::findOrFail($id);

        $validated = $request->validate([
            'pos_customer_id' => 'sometimes|required|integer',
            'pos_product_id' => 'sometimes|required|integer',
            'pos_channel_id' => 'sometimes|required|integer',
            'pos_payment_id' => 'sometimes|required|integer',
            'pos_admin_id' => 'sometimes|required|integer',
            'price' => 'sometimes|required|numeric',
            'link' => 'nullable|string',
            'date' => 'sometimes|required|date',
            'ship_date' => 'nullable|date',
            'note' => 'nullable|string',
            'referral_code' => 'nullable|string',
        ]);

        $posSale->update($validated);

        return response()->json($posSale->load(['customer', 'product', 'channel', 'payment', 'admin']));
    }

    public function destroy($id)
    {
        $posSale = PosSale::findOrFail($id);

        $posSale->delete();

        return response()->json(null, 204);
    }

}
