<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Segment;
use App\Models\SegmentCriteria;
use App\Services\SegmentCriteriaService;
use Illuminate\Http\Request;

class SegmentController extends Controller
{
    protected $segmentCriteriaService;

    public function __construct(SegmentCriteriaService $segmentCriteriaService)
    {
        $this->segmentCriteriaService = $segmentCriteriaService;
    }
    /**
     * Get all segments for the current tenant
     */
    public function index(Request $request)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $segments = Segment::where('tenant_id', $tenantId)
                ->orderBy('created_at', 'desc')
                ->get();

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

    /**
     * Create a new segment
     */
    public function store(Request $request)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            // Validation
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'description' => 'required|string',
                'color' => 'nullable|string|max:7',
                'criteria' => 'nullable|string',
                'customer_count' => 'nullable|integer|min:0'
            ]);

            $segment = Segment::create([
                'tenant_id' => $tenantId,
                'name' => $validated['name'],
                'description' => $validated['description'],
                'color' => $validated['color'] ?? '#007bff',
                'criteria' => $validated['criteria'] ?? '',
                'customer_count' => $validated['customer_count'] ?? 0,
                'avg_ride_frequency' => '0 rides/month',
                'avg_spending' => '₹0/month',
                'retention' => '0%',
                'created_by' => $user->id
            ]);

            return response()->json([
                'success' => true,
                'data' => $segment,
                'message' => 'Segment created successfully'
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create segment',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get a specific segment
     */
    public function show(Request $request, $id)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $segment = Segment::where('tenant_id', $tenantId)
                ->find($id);

            if (!$segment) {
                return response()->json([
                    'success' => false,
                    'message' => 'Segment not found'
                ], 404);
            }

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

    /**
     * Update a segment
     */
    public function update(Request $request, $id)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $segment = Segment::where('tenant_id', $tenantId)
                ->find($id);

            if (!$segment) {
                return response()->json([
                    'success' => false,
                    'message' => 'Segment not found'
                ], 404);
            }

            // Validation
            $validated = $request->validate([
                'name' => 'sometimes|required|string|max:255',
                'description' => 'sometimes|required|string',
                'color' => 'nullable|string|max:7',
                'criteria' => 'nullable|string',
                'customer_count' => 'nullable|integer|min:0',
                'avg_ride_frequency' => 'nullable|string',
                'avg_spending' => 'nullable|string',
                'retention' => 'nullable|string'
            ]);

            $segment->update($validated);

            return response()->json([
                'success' => true,
                'data' => $segment,
                'message' => 'Segment updated successfully'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update segment',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete a segment
     */
    public function destroy(Request $request, $id)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $segment = Segment::where('tenant_id', $tenantId)
                ->find($id);

            if (!$segment) {
                return response()->json([
                    'success' => false,
                    'message' => 'Segment not found'
                ], 404);
            }

            $segment->delete();

            return response()->json([
                'success' => true,
                'message' => 'Segment deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete segment',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all members of a segment and calculate their metrics
     */
    public function getSegmentMembers(Request $request, $segmentId)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $result = $this->segmentCriteriaService->getSegmentMembers($segmentId, $tenantId);
            
            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get segment members',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get segments that a specific passenger belongs to
     */
    public function getPassengerSegments(Request $request, $passengerId)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $result = $this->segmentCriteriaService->getPassengerSegments($passengerId, $tenantId);
            
            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get passenger segments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get or create segment criteria
     */
    public function getSegmentCriteria(Request $request, $segmentId)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $segment = Segment::where('id', $segmentId)
                ->where('tenant_id', $tenantId)
                ->first();

            if (!$segment) {
                return response()->json([
                    'success' => false,
                    'message' => 'Segment not found'
                ], 404);
            }

            $criteria = SegmentCriteria::where('segment_id', $segmentId)
                ->where('tenant_id', $tenantId)
                ->first();

            if (!$criteria) {
                // Return empty criteria template
                $criteria = [
                    'segment_id' => $segmentId,
                    'min_total_trips' => 0,
                    'min_total_spent' => null,
                    'max_total_spent' => null,
                    'min_avg_rating' => null,
                    'payment_method_required' => false,
                    'phone_verified_required' => false,
                    'preferred_trip_types' => [],
                    'inactive_days_threshold' => null,
                    'active_months_lookback' => 3
                ];
            }

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

    /**
     * Create or update segment criteria
     */
    public function updateSegmentCriteria(Request $request, $segmentId)
    {
        try {
            $user = auth('api')->user();
            
            // Get the user's tenant
            $tenantId = $user && isset($user->tenant_id) ? $user->tenant_id : null;
            
            if (!$tenantId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tenant ID not found'
                ], 401);
            }

            $segment = Segment::where('id', $segmentId)
                ->where('tenant_id', $tenantId)
                ->first();

            if (!$segment) {
                return response()->json([
                    'success' => false,
                    'message' => 'Segment not found'
                ], 404);
            }

            // Validation
            $validated = $request->validate([
                'min_total_trips' => 'nullable|integer|min:0',
                'max_total_trips' => 'nullable|integer|min:0',
                'min_total_spent' => 'nullable|numeric|min:0',
                'max_total_spent' => 'nullable|numeric|min:0',
                'min_avg_fare' => 'nullable|numeric|min:0',
                'max_avg_fare' => 'nullable|numeric|min:0',
                'min_avg_rating' => 'nullable|numeric|min:0|max:5',
                'payment_method_required' => 'nullable|boolean',
                'phone_verified_required' => 'nullable|boolean',
                'preferred_trip_types' => 'nullable|array',
                'inactive_days_threshold' => 'nullable|integer|min:1',
                'active_months_lookback' => 'nullable|integer|min:1',
                'behavioral_rules' => 'nullable|array'
            ]);

            // Find or create criteria
            $criteria = SegmentCriteria::where('segment_id', $segmentId)
                ->where('tenant_id', $tenantId)
                ->firstOrNew();

            $criteria->fill(array_merge(
                $validated,
                [
                    'segment_id' => $segmentId,
                    'tenant_id' => $tenantId
                ]
            ));

            $criteria->save();

            return response()->json([
                'success' => true,
                'data' => $criteria,
                'message' => 'Criteria updated successfully'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update criteria',
                'error' => $e->getMessage()
            ], 500);
        }
    }}