<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Models\RcicRegistry;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class RcicRegistryController extends Controller
{
    /**
     * Display a listing of RCIC registries.
     */
    public function index(Request $request)
    {
        $query = RcicRegistry::query();

        // Search functionality
        if ($request->has('search') && $request->search) {
            $query->search($request->search);
        }

        // Filter by type
        if ($request->has('type') && $request->type) {
            $query->where('type', $request->type);
        }

        // Sorting
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        // Pagination
        $perPage = $request->get('per_page', 15);
        $rcics = $query->paginate($perPage);

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

    /**
     * Store a newly created RCIC registry.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'college_id' => 'nullable|unique:rcic_registries,college_id',
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'type' => 'nullable|string|max:255',
            'employment_company' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
        ]);

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

        $rcic = RcicRegistry::create($request->all());

        return response()->json([
            'success' => true,
            'message' => 'RCIC registry created successfully',
            'data' => $rcic
        ], 201);
    }

    /**
     * Display the specified RCIC registry.
     */
    public function show(string $id)
    {
        $rcic = RcicRegistry::find($id);

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

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

    /**
     * Update the specified RCIC registry.
     */
    public function update(Request $request, string $id)
    {
        $rcic = RcicRegistry::find($id);

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

        $validator = Validator::make($request->all(), [
            'college_id' => 'nullable|unique:rcic_registries,college_id,' . $id,
            'name' => 'required|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'type' => 'nullable|string|max:255',
            'employment_company' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
        ]);

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

        $rcic->update($request->all());

        return response()->json([
            'success' => true,
            'message' => 'RCIC registry updated successfully',
            'data' => $rcic->fresh()
        ]);
    }

    /**
     * Remove the specified RCIC registry.
     */
    public function destroy(string $id)
    {
        $rcic = RcicRegistry::find($id);

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

        $rcic->delete();

        return response()->json([
            'success' => true,
            'message' => 'RCIC registry deleted successfully'
        ]);
    }

    /**
     * Import RCIC registries from CSV.
     */
    public function import(Request $request)
    {
        // Increase execution time and memory for large imports
        set_time_limit(300); // 5 minutes
        ini_set('memory_limit', '512M');
        
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|mimes:csv,txt|max:10240', // 10MB max
        ]);

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

        $file = $request->file('file');
        $handle = fopen($file->getRealPath(), 'r');
        
        // Count total rows
        $totalRows = 0;
        while (fgetcsv($handle) !== false) {
            $totalRows++;
        }
        
        // Reset file pointer to start
        rewind($handle);
        
        $imported = 0;
        $errors = [];
        $skipped = 0;
        $rowNumber = 0;
        $batchData = [];
        $batchSize = 500; // Insert 500 records at a time for better performance

        while (($row = fgetcsv($handle)) !== false) {
            $rowNumber++;
            
            // Skip empty rows
            if (empty(array_filter($row))) {
                continue;
            }

            try {
                // CSV Structure:
                // 0: College ID (R710673)
                // 1: Name (Full Name)
                // 2: Company Name
                // 3: Type (RCIC - L1, RCIC - L2, RCIC-IRB - L3)
                // 4: Employment Company
                // 5: Email
                
                $data = [
                    'college_id' => isset($row[0]) && $row[0] !== 'NULL' ? trim($row[0]) : null,
                    'name' => isset($row[1]) && $row[1] !== 'NULL' ? trim($row[1]) : 'N/A',
                    'company_name' => isset($row[2]) && $row[2] !== 'NULL' ? trim($row[2]) : null,
                    'type' => isset($row[3]) && $row[3] !== 'NULL' ? trim($row[3]) : null,
                    'employment_company' => isset($row[4]) && $row[4] !== 'NULL' ? trim($row[4]) : null,
                    'email' => isset($row[5]) && $row[5] !== 'NULL' ? trim($row[5]) : null,
                ];

                // Validate required fields
                if (empty($data['name']) || $data['name'] === 'N/A') {
                    $errors[] = "Row {$rowNumber}: Name is required";
                    $skipped++;
                    continue;
                }

                // Add timestamps as string format for batch insert
                $now = date('Y-m-d H:i:s');
                $data['created_at'] = $now;
                $data['updated_at'] = $now;

                // Add to batch
                $batchData[] = $data;
                $imported++;

                // Insert batch when reaching batch size
                if (count($batchData) >= $batchSize) {
                    try {
                        DB::table('rcic_registries')->insert($batchData);
                    } catch (\Exception $batchError) {
                        Log::error('Batch insert failed: ' . $batchError->getMessage());
                        // Try individual inserts if batch fails
                        foreach ($batchData as $item) {
                            try {
                                DB::table('rcic_registries')->insert($item);
                            } catch (\Exception $itemError) {
                                $errors[] = "Batch insert error: " . $itemError->getMessage();
                                $skipped++;
                                $imported--;
                            }
                        }
                    }
                    $batchData = [];
                }
            } catch (\Exception $e) {
                $errors[] = "Row {$rowNumber}: " . $e->getMessage();
                $skipped++;
                if ($imported > 0) $imported--;
            }
        }

        // Insert any remaining records in the batch
        if (count($batchData) > 0) {
            try {
                DB::table('rcic_registries')->insert($batchData);
            } catch (\Exception $batchError) {
                Log::error('Final batch insert failed: ' . $batchError->getMessage());
                // Try individual inserts if batch fails
                foreach ($batchData as $item) {
                    try {
                        DB::table('rcic_registries')->insert($item);
                    } catch (\Exception $itemError) {
                        $errors[] = "Final batch error: " . $itemError->getMessage();
                        $skipped++;
                        if ($imported > 0) $imported--;
                    }
                }
            }
        }

        fclose($handle);

        return response()->json([
            'success' => true,
            'message' => "Successfully imported {$imported} RCIC registries" . ($skipped > 0 ? ", {$skipped} skipped" : ""),
            'total_rows' => $totalRows,
            'imported' => $imported,
            'skipped' => $skipped,
            'errors' => count($errors) > 100 ? array_slice($errors, 0, 100) : $errors,
            'total_errors' => count($errors)
        ]);
    }

    /**
     * Export RCIC registries to CSV.
     */
    public function export(Request $request)
    {
        $query = RcicRegistry::query();

        // Apply same filters as index
        if ($request->has('search') && $request->search) {
            $query->search($request->search);
        }

        if ($request->has('type') && $request->type) {
            $query->where('type', $request->type);
        }

        $rcics = $query->orderBy('college_id')->get();

        $filename = 'rcic_registries_' . date('Y-m-d_His') . '.csv';
        $handle = fopen('php://temp', 'w');

        // Add CSV header
        fputcsv($handle, [
            'College ID',
            'Name',
            'Company Name',
            'Type',
            'Employment Company',
            'Email',
            'Created At',
            'Updated At'
        ]);

        // Add data rows
        foreach ($rcics as $rcic) {
            fputcsv($handle, [
                $rcic->college_id,
                $rcic->name,
                $rcic->company_name,
                $rcic->type,
                $rcic->employment_company,
                $rcic->email,
                $rcic->created_at?->format('Y-m-d H:i:s'),
                $rcic->updated_at?->format('Y-m-d H:i:s'),
            ]);
        }

        rewind($handle);
        $csv = stream_get_contents($handle);
        fclose($handle);

        return response($csv, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }

    /**
     * Delete all RCIC registries.
     */
    public function deleteAll(Request $request)
    {
        try {
            $count = RcicRegistry::count();
            RcicRegistry::truncate();

            return response()->json([
                'success' => true,
                'message' => "Successfully deleted {$count} RCIC registries"
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to delete all RCIC registries: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete RCIC registries'
            ], 500);
        }
    }
}
