<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\CreditSeedMonitoring;
use Illuminate\Http\Request;

class CreditSeedMonitoringController extends Controller
{
    // Store monitoring data
public function store(Request $request)
{
    $request->validate([
        'client_id'       => 'required|integer',
        'credit_id'       => 'required|integer',
        'title'           => 'required|string|max:255',
        'location'        =>'required',
        'monitoring_type' => 'required|in:crop_health,pest_monitoring,soil_analysis,growth_stage,irrigation,harvest,field_observation,equipment_check',
        'crop_stage'      => 'nullable|in:germination,vegetative,flowering,fruiting,maturity,harvest',
        'latitude'        => 'nullable|numeric|between:-90,90',
        'longitude'       => 'nullable|numeric|between:-180,180',
        'observations'    => 'nullable|string',
        'photo'           => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
    ]);

    $data = $request->all();

    // ✅ Handle photo upload
    if ($request->hasFile('photo')) {
        $filename = time() . '_' . $request->file('photo')->getClientOriginalName();
        $path = $request->file('photo')->storeAs('monitoring_photos', $filename, 'public');
        $data['photo'] = $path;
    }

    // ✅ Add created_by automatically
    $data['createdby'] = auth()->id();

    $monitoring = CreditSeedMonitoring::create($data);

    return response()->json([
        'message' => 'Monitoring record created successfully',
        'data'    => $monitoring
    ], 201);
}


public function index()
{
    $records = CreditSeedMonitoring::with('client')
        ->latest()
        ->get()
        ->map(function ($record) {

            // Set client name
            $record->client_name = $record->client ? $record->client->name : 'Unnamed Client';

            // Generate full URL for photo if it exists
            if ($record->photo) {
                // Remove duplicate folder prefix if present
                $photoPath = preg_replace('#^(monitoring_photos/)+#', '', $record->photo);

                // Generate URL and encode spaces/special characters
                $record->photo = url('storage/monitoring_photos/' . $photoPath);
            } else {
                $record->photo = null;
            }

            // Remove the client relationship to reduce payload
            unset($record->client);

            return $record;
        });

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


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

    $query = CreditSeedMonitoring::with('client');

    // Filter by client_id if provided
    if ($clientId) {
        $query->where('client_id', $clientId);
    }

    $records = $query->latest()->get()->map(function ($record) {
        // Set client name
        $record->client_name = $record->client ? $record->client->name : 'Unnamed Client';

        // Generate full URL for photo if it exists
        if ($record->photo) {
            // Remove duplicate folder prefix if present
            $photoPath = preg_replace('#^(monitoring_photos/)+#', '', $record->photo);

            // Generate full URL (Laravel handles spaces/special chars)
            $record->photo = url('storage/monitoring_photos/' . $photoPath);
        } else {
            $record->photo = null;
        }

        // Remove the client relationship to reduce payload
        unset($record->client);

        return $record;
    });

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




}
