<?php

namespace App\Http\Controllers\Api;

use App\Models\HealthScore;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class HealthScoreController extends Controller
{
    /**
     * Display a listing of health scores
     */
    public function index(Request $request)
    {
        try {
            $tenantId = auth()->user()->tenant_id;

            $query = HealthScore::where('tenant_id', $tenantId);

            // Apply filters if provided
            if ($request->has('status')) {
                $query->where('status', $request->query('status'));
            }

            if ($request->has('search')) {
                $search = $request->query('search');
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%$search%")
                        ->orWhere('email', 'like', "%$search%");
                });
            }

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

            return response()->json([
                'success' => true,
                'data' => $scores
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching health scores: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a newly created health score
     */
    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'customer_id' => 'required|string',
                'name' => 'required|string',
                'email' => 'required|email',
                'phone' => 'required|string',
                'overall_score' => 'required|integer|between:0,100',
                'metrics' => 'required',
                'status' => 'required|in:excellent,good,at_risk,critical',
                'last_ride' => 'nullable|string',
                'total_rides' => 'required|integer',
                'total_spending' => 'nullable|string',
                'trends' => 'required|in:improving,stable,declining',
                'recommendations' => 'nullable'
            ]);

            $validated['tenant_id'] = auth()->user()->tenant_id;
            $validated['created_by'] = auth()->user()->id;

            $score = HealthScore::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Health score created successfully',
                'data' => $score
            ], 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' => 'Error creating health score: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified health score
     */
    public function show($id)
    {
        try {
            $tenantId = auth()->user()->tenant_id;
            $score = HealthScore::where('tenant_id', $tenantId)->findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => $score
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Health score not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching health score: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update the specified health score
     */
    public function update(Request $request, $id)
    {
        try {
            $tenantId = auth()->user()->tenant_id;
            $score = HealthScore::where('tenant_id', $tenantId)->findOrFail($id);

            $validated = $request->validate([
                'customer_id' => 'sometimes|string',
                'name' => 'sometimes|string',
                'email' => 'sometimes|email',
                'phone' => 'sometimes|string',
                'overall_score' => 'sometimes|integer|between:0,100',
                'metrics' => 'sometimes',
                'status' => 'sometimes|in:excellent,good,at_risk,critical',
                'last_ride' => 'nullable|string',
                'total_rides' => 'sometimes|integer',
                'total_spending' => 'nullable|string',
                'trends' => 'sometimes|in:improving,stable,declining',
                'recommendations' => 'nullable'
            ]);

            $score->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Health score updated successfully',
                'data' => $score
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Health score not found'
            ], 404);
        } 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' => 'Error updating health score: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete the specified health score
     */
    public function destroy($id)
    {
        try {
            $tenantId = auth()->user()->tenant_id;
            $score = HealthScore::where('tenant_id', $tenantId)->findOrFail($id);

            $score->delete();

            return response()->json([
                'success' => true,
                'message' => 'Health score deleted successfully'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Health score not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting health score: ' . $e->getMessage()
            ], 500);
        }
    }
}
