<?php

namespace App\Http\Controllers\Api\Admin;

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

class KycApiController extends Controller
{
    /**
     * Get all KYC records (matching original logic)
     */
    public function index(Request $request)
    {
        try {
            $kyc_records_query = KycRecord::get();
            $kyc_summary = [
                'approved' => $kyc_records_query->where('status', 'approved')->count(),
                'rejected' => $kyc_records_query->where('status', 'rejected')->count(),
                'pending' => $kyc_records_query->where('status', 'pending')->count()
            ];
            $kyc_records = KycRecord::orderBy('id', 'DESC')->with('user')->paginate(10);

            return response()->json([
                'status' => 'success',
                'data' => $kyc_records,
                'summary' => $kyc_summary
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch KYC records',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get specific KYC record details (matching original viewKyc)
     */
    public function show($id)
    {
        try {
            $record = KycRecord::with('user')->where('id', $id)->first();
            if (!$record) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'KYC Record not found'
                ], 404);
            }

            return response()->json([
                'status' => 'success',
                'data' => $record
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'KYC verification not found',
                'error' => $e->getMessage()
            ], 404);
        }
    }

    /**
     * Process KYC record (approve/reject/delete - matching original logic)
     */
    public function process(Request $request, $id)
    {
        try {
            $request->validate([
                'action' => 'required'
            ]);

            $action = $request->action;
            $document_id = $id;
            $record = KycRecord::find($document_id);
            if (!$record) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'KYC record not found'
                ], 422);
            }

            $user = User::find($record->user->id);

            if ($action == 'delete') {
                $record->delete();
                return response()->json([
                    'status' => 'success',
                    'message' => 'Record Deleted successfully'
                ]);
            } elseif ($action == 'approve') {
                $record->status = 'approved';
                $record->save();

                $user->kyc_verified_at = now();
                $user->save();
                return response()->json([
                    'status' => 'success',
                    'message' => 'Record approved successfully'
                ]);
            } elseif ($action == 'reject') {
                $record->status = 'rejected';
                $record->save();

                $user->kyc_verified_at = null;
                $user->save();
                return response()->json([
                    'status' => 'success',
                    'message' => 'Record rejected successfully'
                ]);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Unknown action'
                ], 422);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to process KYC record',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update KYC record details
     */
    public function update(Request $request, $id)
    {
        try {
            $record = KycRecord::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'first_name' => 'sometimes|string|max:100',
                'last_name' => 'sometimes|string|max:100',
                'document_type' => 'sometimes|string|max:50',
                'document_number' => 'sometimes|string|max:50',
                'admin_note' => 'nullable|string|max:1000'
            ]);

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

            if ($record->status === 'approved') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot modify approved KYC records'
                ], 400);
            }

            $record->update($validator->validated());

            return response()->json([
                'status' => 'success',
                'message' => 'KYC record updated successfully',
                'data' => $record
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to update KYC record',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete KYC record
     */
    public function destroy($id)
    {
        try {
            $record = KycRecord::findOrFail($id);
            
            if ($record->status === 'approved') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot delete approved KYC records'
                ], 400);
            }

            $record->delete();

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

    /**
     * Get KYC statistics
     */
    public function statistics(Request $request)
    {
        try {
            $period = $request->period ?? 'all';
            
            $query = KycRecord::query();
            
            switch ($period) {
                case 'today':
                    $query->whereDate('created_at', today());
                    break;
                case 'week':
                    $query->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]);
                    break;
                case 'month':
                    $query->whereMonth('created_at', now()->month);
                    break;
                case 'year':
                    $query->whereYear('created_at', now()->year);
                    break;
            }

            $stats = [
                'total_kyc' => $query->count(),
                'pending_kyc' => $query->where('status', 'pending')->count(),
                'approved_kyc' => $query->where('status', 'approved')->count(),
                'rejected_kyc' => $query->where('status', 'rejected')->count(),
                'verification_rate' => $query->count() > 0 ? 
                    round(($query->where('status', 'approved')->count() / $query->count()) * 100, 2) : 0,
                'document_types' => KycRecord::selectRaw('document_type, COUNT(*) as count')
                                             ->groupBy('document_type')
                                             ->get(),
            ];

            return response()->json([
                'status' => 'success',
                'data' => $stats,
                'period' => $period
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch KYC statistics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk process KYC records
     */
    public function bulkProcess(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'action' => 'required|in:approve,reject',
                'kyc_ids' => 'required|array',
                'kyc_ids.*' => 'exists:kyc_records,id',
                'reason' => 'nullable|string|max:500'
            ]);

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

            $kycIds = $request->kyc_ids;
            $action = $request->action;
            $processedCount = 0;

            $kycs = KycRecord::whereIn('id', $kycIds)
                            ->where('status', 'pending')
                            ->get();

            foreach ($kycs as $kyc) {
                if ($action === 'approve') {
                    $kyc->status = 'approved';
                    $kyc->save();

                    // Update user KYC status
                    $kyc->user->kyc_verified_at = now();
                    $kyc->user->save();
                } else {
                    $kyc->status = 'rejected';
                    $kyc->save();

                    // Ensure user KYC status is null
                    $kyc->user->kyc_verified_at = null;
                    $kyc->user->save();
                }
                $processedCount++;
            }

            return response()->json([
                'status' => 'success',
                'message' => "Bulk {$action} completed successfully",
                'processed_count' => $processedCount
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to perform bulk process',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}