<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ProfitEstimation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ProfitEstimationController extends Controller
{

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'order_id' => 'required|integer',
        'client_id' => 'nullable|integer',
        'seed_id' => 'nullable|integer',
        'area_size' => 'required|numeric|min:0',
        'estimated_revenue' => 'required|numeric|min:0',
        'estimated_costs' => 'required|numeric|min:0',
        'estimated_profit' => 'required|numeric',
        'production_per_ha' => 'required|numeric|min:0',
        'sale_price' => 'required|numeric|min:0',
        'calculation_date' => 'required|date'
    ]);

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

    try {
        // ✅ Get authenticated user ID
        $userId = auth()->id();
        
        // ✅ Merge createdby with request data
        $data = array_merge($request->all(), ['createdby' => $userId]);
        
        // ✅ Check if both client_id and seed_id are provided and not null
        if (!empty($data['client_id']) && !empty($data['seed_id'])) {
            // ✅ Use updateOrCreate to update existing record or create new one
            $profitEstimation = ProfitEstimation::updateOrCreate(
                [
                    'client_id' => $data['client_id'],
                    'seed_id' => $data['seed_id']
                ],
                $data
            );
            
            $message = $profitEstimation->wasRecentlyCreated ? 
                'Profit estimation created successfully' : 
                'Profit estimation updated successfully';
        } else {
            // ✅ If either client_id or seed_id is missing, just create new record
            $profitEstimation = ProfitEstimation::create($data);
            $message = 'Profit estimation created successfully';
        }

        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $profitEstimation,
            'action' => $profitEstimation->wasRecentlyCreated ? 'created' : 'updated'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to save profit estimation',
            'error' => $e->getMessage()
        ], 500);
    }
}
public function harvestEstimated(Request $request)
    {
        $clientId = $request->query('client_id');
        $seedId   = $request->query('seed_id');

        $query = ProfitEstimation::query();

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

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

        $estimations = $query->get();

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


    public function show($orderId)
    {
        try {
            $profitEstimation = ProfitEstimation::with(['order', 'client', 'seed'])
                ->where('order_id', $orderId)
                ->first();

            if (!$profitEstimation) {
                return response()->json([
                    'success' => false,
                    'message' => 'Profit estimation not found for this order'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $profitEstimation
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve profit estimation',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function byClient($clientId)
    {
        try {
            $profitEstimations = ProfitEstimation::with(['order', 'seed'])
                ->where('client_id', $clientId)
                ->orderBy('calculation_date', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $profitEstimations
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve profit estimations',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    // Optional: Additional methods for filtering and management
    public function index(Request $request)
    {
        try {
            $query = ProfitEstimation::with(['order', 'client', 'seed']);
            
            // Filter by date range if provided
            if ($request->has('start_date') && $request->has('end_date')) {
                $query->whereBetween('calculation_date', [
                    $request->start_date,
                    $request->end_date
                ]);
            }
            
            // Filter by client if provided
            if ($request->has('client_id')) {
                $query->where('client_id', $request->client_id);
            }
            
            $profitEstimations = $query->orderBy('calculation_date', 'desc')->paginate(20);
            
            return response()->json([
                'success' => true,
                'data' => $profitEstimations
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve profit estimations',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $profitEstimation = ProfitEstimation::findOrFail($id);
            $profitEstimation->delete();
            
            return response()->json([
                'success' => true,
                'message' => 'Profit estimation deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete profit estimation',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}