<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ClientContributionSummary;
use App\Models\OrderAdditionalCost;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class ClientContributionController extends Controller

{

public function store(Request $request)
{
    // Validate the request
  


    DB::beginTransaction();

    try {
        $inserted = [];
        foreach ($request->contributions as $contribution) {
            $summary = ClientContributionSummary::create([
                'client_id' => $request->client_id,
                'client_name' => $request->client_name,
                'area_size' => $request->area_size,
                'seed_id' => $request->seed_id,
                'seed_name' => $request->seed_name,
                'total_contribution' => $request->gross_total - $request->net_total,
                'gross_total' => $request->gross_total,
                'net_total' => $request->net_total,
                'order_id' => $request->order_id,
                'visit_id' => $request->visit_id,
                'category' => $contribution['category'],
                'item_name' => $contribution['item_name'],
                'unit' => $contribution['unit'],
                'quantity' => $contribution['quantity'],
                'unit_price' => $contribution['unit_price'],
                'total_price' => $contribution['total_price'],
            ]);
            $inserted[] = $summary;
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'data' => $inserted,
            'message' => 'Contributions saved successfully'
        ], 201);

    } catch (\Exception $e) {
        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Failed to save contributions',
            'error' => $e->getMessage()
        ], 500);
    }
}

    /**
     * Get contributions for a client and order
     */

  public function index(Request $request)
{
    $clientId = $request->query('client_id');
    $seedId   = $request->query('seed_id');

    $query = ClientContributionSummary::query();

    // Apply filters if provided
    if (!empty($clientId)) {
        $query->where('client_id', $clientId);
    }

    if (!empty($seedId)) {
        $query->where('seed_id', $seedId);
    }

    $summaries = $query->get();

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

    public function clientAddition(Request $request){
    $clientId = $request->query('client_id');
    $seedId   = $request->query('seed_id');

    $query = OrderAdditionalCost::query();

    // Apply filters if provided
    if (!empty($clientId)) {
        $query->where('client_id', $clientId);
    }

    if (!empty($seedId)) {
        $query->where('seed_id', $seedId);
    }

    $summaries = $query->get();

    return response()->json($summaries);

    }
}