<?php

namespace App\Http\Controllers\Api;

use App\Models\Accessory;
use App\Models\AccessoryPurchase;
use App\Models\AccessoryStockMovement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;

class AccessoryPurchaseController extends Controller
{
    public function index(Request $request)
    {
        $query = AccessoryPurchase::with(['accessory', 'supplier']);

        // Filter by accessory
        if ($request->has('accessory_id')) {
            $query->where('accessory_id', $request->accessory_id);
        }

        // Filter by supplier
        if ($request->has('supplier_id')) {
            $query->where('supplier_id', $request->supplier_id);
        }

        // Filter by date range
        if ($request->has('from_date')) {
            $query->whereDate('purchase_date', '>=', $request->from_date);
        }
        if ($request->has('to_date')) {
            $query->whereDate('purchase_date', '<=', $request->to_date);
        }

        $purchases = $query->orderBy('purchase_date', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($purchases);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'accessory_id' => 'required|exists:accessories,id',
            'supplier_id' => 'nullable|exists:suppliers,id',
            'quantity' => 'required|integer|min:1',
            'unit_price' => 'required|numeric|min:0',
            'gst_percentage' => 'nullable|numeric|min:0|max:100',
            'purchase_date' => 'required|date',
            'invoice_number' => 'nullable|string|max:255',
            'notes' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        try {
            DB::beginTransaction();

            // Calculate amounts
            $quantity = $request->quantity;
            $unitPrice = $request->unit_price;
            $totalAmount = $quantity * $unitPrice;
            $gstPercentage = $request->gst_percentage ?? 0;
            $gstAmount = ($totalAmount * $gstPercentage) / 100;
            $grandTotal = $totalAmount + $gstAmount;

            // Create purchase record
            $purchase = AccessoryPurchase::create([
                'accessory_id' => $request->accessory_id,
                'supplier_id' => $request->supplier_id,
                'quantity' => $quantity,
                'unit_price' => $unitPrice,
                'total_amount' => $totalAmount,
                'gst_amount' => $gstAmount,
                'grand_total' => $grandTotal,
                'purchase_date' => $request->purchase_date,
                'invoice_number' => $request->invoice_number,
                'notes' => $request->notes
            ]);

            // Update accessory stock
            $accessory = Accessory::findOrFail($request->accessory_id);
            $stockBefore = $accessory->current_stock;
            $stockAfter = $stockBefore + $quantity;
            
            $accessory->update([
                'current_stock' => $stockAfter,
                'purchase_price' => $unitPrice // Update purchase price
            ]);

            // Create stock movement record
            AccessoryStockMovement::create([
                'accessory_id' => $accessory->id,
                'type' => 'purchase',
                'quantity' => $quantity,
                'stock_before' => $stockBefore,
                'stock_after' => $stockAfter,
                'reference_id' => $purchase->id,
                'reference_type' => AccessoryPurchase::class,
                'notes' => "Purchase: {$quantity} units added"
            ]);

            DB::commit();

            $purchase->load(['accessory', 'supplier']);

            return response()->json([
                'message' => 'Purchase recorded successfully',
                'purchase' => $purchase
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'Failed to record purchase',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        $purchase = AccessoryPurchase::with(['accessory', 'supplier', 'stockMovement'])
            ->findOrFail($id);

        return response()->json($purchase);
    }

    public function destroy($id)
    {
        try {
            DB::beginTransaction();

            $purchase = AccessoryPurchase::findOrFail($id);
            
            // Check if we can reverse the stock
            $accessory = $purchase->accessory;
            if ($accessory->current_stock < $purchase->quantity) {
                return response()->json([
                    'message' => 'Cannot delete purchase. Insufficient stock to reverse the transaction.'
                ], 400);
            }

            // Update stock
            $stockBefore = $accessory->current_stock;
            $stockAfter = $stockBefore - $purchase->quantity;
            
            $accessory->update([
                'current_stock' => $stockAfter
            ]);

            // Create stock movement for reversal
            AccessoryStockMovement::create([
                'accessory_id' => $accessory->id,
                'type' => 'adjustment',
                'quantity' => -$purchase->quantity,
                'stock_before' => $stockBefore,
                'stock_after' => $stockAfter,
                'notes' => "Purchase deleted: {$purchase->quantity} units removed"
            ]);

            // Delete the purchase
            $purchase->delete();

            DB::commit();

            return response()->json([
                'message' => 'Purchase deleted successfully'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'Failed to delete purchase',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}