<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Worker;
use App\Models\Conversation;
use App\Models\Review;

class ReportController extends Controller
{
    /**
     * Submit a report from a worker.
     * POST /api/workers/report
     */
    public function reportFromWorker(Request $request)
    {
        /** @var Worker $worker */
        $worker = $request->attributes->get('worker');

        $validator = Validator::make($request->all(), [
            'type' => 'required|in:Chat,Review',
            'item_id' => 'required',
            'user_id' => 'nullable',
            'reason' => 'required|string|max:255',
            'others' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:2000',
        ]);

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

        try {
            $reportedName = '';
            $reportedRole = 'Sponsor';
            $reportedAvatar = null;

            if ($request->type === 'Chat') {
                $conversation = Conversation::where('id', $request->item_id)
                    ->where('worker_id', $worker->id)
                    ->first();

                if (!$conversation) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Conversation not found or unauthorized.'
                    ], 404);
                }

                $employer = $conversation->employer;
                if (!$employer) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Employer associated with the conversation not found.'
                    ], 404);
                }

                $reportedName = $employer->name;
            } else {
                // Review
                $review = Review::where('id', $request->item_id)
                    ->where('worker_id', $worker->id)
                    ->first();

                if (!$review) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Review not found or unauthorized.'
                    ], 404);
                }

                $employer = User::find($review->employer_id);
                if (!$employer) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Employer associated with the review not found.'
                    ], 404);
                }

                $reportedName = $employer->name;
            }

            $reportId = 'REP-' . Str::upper(Str::random(8));

            $actualReason = $request->reason;
            if (strtolower($request->reason) === 'others' && $request->filled('others')) {
                $actualReason = 'Others: ' . $request->others;
            }

            // Insert to moderation_reports
            DB::table('moderation_reports')->insert([
                'id' => $reportId,
                'type' => $request->type,
                'reported_user_id' => $request->user_id,
                'reported_user_name' => $reportedName,
                'reported_user_role' => $reportedRole,
                'reported_user_avatar' => $reportedAvatar,
                'reported_by_name' => $worker->name,
                'reported_by_role' => 'Worker',
                'reported_by_avatar' => null,
                'reason' => $actualReason,
                'priority' => 'Medium',
                'status' => 'Pending',
                'description' => $request->description,
                'reported_at' => now(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            // Add Audit Log
            DB::table('audit_logs')->insert([
                'category' => 'user_activity',
                'user' => $worker->name . ' (Worker)',
                'action' => 'Submitted Safety Report ' . $reportId . ' on ' . $reportedName . ' (Type: ' . $request->type . ', Reason: ' . $request->reason . ')',
                'ip_address' => $request->ip() ?: '127.0.0.1',
                'created_at' => now(),
                'updated_at' => now()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Report submitted successfully. Our safety team will review it shortly.',
                'report_id' => $reportId
            ], 201);

        } catch (\Exception $e) {
            logger()->error('Worker API Report Submission Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while submitting the report.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Submit a report from an employer.
     * POST /api/employers/report
     */
    public function reportFromEmployer(Request $request)
    {
        /** @var User $employer */
        $employer = $request->attributes->get('employer');

        $validator = Validator::make($request->all(), [
            'type' => 'required|in:Chat,Review',
            'item_id' => 'required',
            'user_id' => 'nullable',
            'reason' => 'required|string|max:255',
            'others' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:2000',
        ]);

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

        try {
            $reportedName = '';
            $reportedRole = 'Worker';
            $reportedAvatar = null;

            if ($request->type === 'Chat') {
                $conversation = Conversation::where('id', $request->item_id)
                    ->where('employer_id', $employer->id)
                    ->first();

                if (!$conversation) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Conversation not found or unauthorized.'
                    ], 404);
                }

                $worker = $conversation->worker;
                if (!$worker) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Worker associated with the conversation not found.'
                    ], 404);
                }

                $reportedName = $worker->name;
            } else {
                // Review
                $review = Review::where('id', $request->item_id)
                    ->where('employer_id', $employer->id)
                    ->first();

                if (!$review) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Review not found or unauthorized.'
                    ], 404);
                }

                $worker = Worker::find($review->worker_id);
                if (!$worker) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Worker associated with the review not found.'
                    ], 404);
                }

                $reportedName = $worker->name;
            }

            $reportId = 'REP-' . Str::upper(Str::random(8));

            $actualReason = $request->reason;
            if (strtolower($request->reason) === 'others' && $request->filled('others')) {
                $actualReason = 'Others: ' . $request->others;
            }

            // Insert to moderation_reports
            DB::table('moderation_reports')->insert([
                'id' => $reportId,
                'type' => $request->type,
                'reported_user_id' => $request->user_id,
                'reported_user_name' => $reportedName,
                'reported_user_role' => $reportedRole,
                'reported_user_avatar' => $reportedAvatar,
                'reported_by_name' => $employer->name,
                'reported_by_role' => 'Sponsor',
                'reported_by_avatar' => null,
                'reason' => $actualReason,
                'priority' => 'Medium',
                'status' => 'Pending',
                'description' => $request->description,
                'reported_at' => now(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            // Add Audit Log
            DB::table('audit_logs')->insert([
                'category' => 'user_activity',
                'user' => $employer->name . ' (Sponsor)',
                'action' => 'Submitted Safety Report ' . $reportId . ' on ' . $reportedName . ' (Type: ' . $request->type . ', Reason: ' . $request->reason . ')',
                'ip_address' => $request->ip() ?: '127.0.0.1',
                'created_at' => now(),
                'updated_at' => now()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Report submitted successfully. Our safety team will review it shortly.',
                'report_id' => $reportId
            ], 201);

        } catch (\Exception $e) {
            logger()->error('Employer API Report Submission Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while submitting the report.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Get active report reasons for workers.
     * GET /api/workers/report-reasons
     */
    public function getReasonsForWorker(Request $request)
    {
        $type = $request->query('type'); // Chat or Review

        $query = DB::table('report_reasons')->where('status', 'Active');

        if ($type && in_array($type, ['Chat', 'Review'])) {
            $query->whereIn('type', [$type, 'Both']);
        }

        $reasons = $query->orderBy('id', 'asc')->get(['id', 'reason', 'type']);

        return response()->json([
            'success' => true,
            'reasons' => $reasons
        ], 200);
    }

    /**
     * Get active report reasons for employers.
     * GET /api/employers/report-reasons
     */
    public function getReasonsForEmployer(Request $request)
    {
        $type = $request->query('type'); // Chat or Review

        $query = DB::table('report_reasons')->where('status', 'Active');

        if ($type && in_array($type, ['Chat', 'Review'])) {
            $query->whereIn('type', [$type, 'Both']);
        }

        $reasons = $query->orderBy('id', 'asc')->get(['id', 'reason', 'type']);

        return response()->json([
            'success' => true,
            'reasons' => $reasons
        ], 200);
    }
}
