<?php

namespace App\Http\Controllers;

use App\Models\Registration;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class ImportController extends Controller
{
    /**
     * Show the form for importing registrations from CSV.
     *
     * @return \Illuminate\Http\Response
     */
    public function showImportForm()
    {
        return view('admin.import');
    }

    /**
     * Process the CSV file and import registrations.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */    public function processImport(Request $request)
    {
        // Remove PHP execution time limit for large imports
        set_time_limit(0);
        
        // Validate file upload
        $request->validate([
            'csv_file' => 'required|file|mimes:csv,txt|max:10240', // Max 10MB
        ], [
            'csv_file.required' => 'Silakan pilih file CSV untuk diimport.',
            'csv_file.file' => 'Upload harus berupa file.',
            'csv_file.mimes' => 'File harus dalam format CSV.',
            'csv_file.max' => 'Ukuran file maksimal 10MB.',
        ]);

        // Process file
        $file = $request->file('csv_file');
        $path = $file->getRealPath();
        $replaceExisting = $request->has('replace_existing');
        
        // Read and process the CSV file
        $registrations = [];
        $errors = [];
        $lineNumber = 0;
        $success = 0;
        $failed = 0;
        $updated = 0;
        
        if (($handle = fopen($path, "r")) !== FALSE) {
            // Read each line of the CSV file
            while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                $lineNumber++;
                
                // Skip header row if present
                if ($lineNumber === 1 && $request->has('has_header')) {
                    continue;
                }
                
                // Verify the number of columns
                if (count($data) < 8) {
                    $errors[] = "Baris $lineNumber: Jumlah kolom kurang dari yang diharapkan.";
                    $failed++;
                    continue;
                }
                
                // Map CSV columns to registration fields
                try {
                    $name = trim($data[0]);
                    $nik = trim($data[1]);
                    $phone = trim($data[2]);
                    $email = trim($data[3]);
                    $disability_note = trim($data[4]);
                    $pendamping = trim($data[5]);
                    $reservationDateTime = trim($data[6]);
                    $topic = trim($data[7]); // Add topic from the CSV
                    
                    // Format phone number to add 62 prefix if needed
                    if (substr($phone, 0, 1) === '0') {
                        $phone = '62' . substr($phone, 1);
                    }
                    
                    // Parse the date and time from format '12/08/2025 11.00'
                    try {
                        $dateTime = Carbon::createFromFormat('d/m/Y H.i', $reservationDateTime);
                        $visitDate = $dateTime->format('Y-m-d');
                        $visitTime = $dateTime->format('H:i');
                    } catch (\Exception $e) {
                        $errors[] = "Baris $lineNumber: Format tanggal dan waktu reservasi tidak valid. Format yang benar: 'DD/MM/YYYY HH.MM'";
                        $failed++;
                        continue;
                    }
                    
                    // Validate required data
                    $validator = Validator::make([
                        'name' => $name,
                        'nik' => $nik,
                        'phone' => $phone,
                        'visit_date' => $visitDate,
                        'visit_time' => $visitTime,
                    ], [
                        'name' => 'required|string|max:255',
                        'nik' => 'required|digits:16',
                        'phone' => 'required|regex:/^62\d+$/',
                        'visit_date' => 'required|date',
                        'visit_time' => 'required|in:08:00,09:00,10:00,11:00',
                    ]);
                    
                    if ($validator->fails()) {
                        foreach ($validator->errors()->all() as $message) {
                            $errors[] = "Baris $lineNumber: $message";
                        }
                        $failed++;
                        continue;
                    }
                    
                    // Check if registration with this NIK already exists
                    $existingRegistration = Registration::where('nik', $nik)->first();
                    
                    if ($existingRegistration && $replaceExisting) {
                        // Update existing registration
                        $existingRegistration->name = $name;
                        $existingRegistration->phone = $phone;
                        $existingRegistration->email = $email ?: $existingRegistration->email;
                        $existingRegistration->topic = $topic ?: $existingRegistration->topic;
                        $existingRegistration->pendamping = $pendamping ?: $existingRegistration->pendamping;
                        $existingRegistration->priority = !empty($disability_note) || !empty($pendamping);
                        $existingRegistration->visit_date = $visitDate;
                        $existingRegistration->visit_time = $visitTime;
                        
                        // Save the updated registration
                        $existingRegistration->save();
                        $updated++;
                    } else if ($existingRegistration && !$replaceExisting) {
                        // Skip if registration exists and replace option is not selected
                        $errors[] = "Baris $lineNumber: NIK $nik sudah terdaftar. Aktifkan opsi 'Replace Data' untuk mengganti data yang sudah ada.";
                        $failed++;
                        continue;
                    } else {
                        // Create new registration
                        $bookingCode = strtoupper(Str::random(6));
                        $registration = new Registration();
                        $registration->booking_code = $bookingCode;
                        $registration->name = $name;
                        $registration->nik = $nik;
                        $registration->phone = $phone;
                        $registration->email = $email ?: null;
                        $registration->topic = $topic ?: 'Imported Registration';
                        $registration->pendamping = $pendamping ?: null;
                        $registration->priority = !empty($disability_note) || !empty($pendamping);
                        $registration->visit_date = $visitDate;
                        $registration->visit_time = $visitTime;
                        $registration->gender = 'L'; // Set gender to L for all imported registrations
                        $registration->no_kk = str_repeat('0', 16); // Default placeholder for No. KK
                        $registration->address = 'Imported Registration'; // Default placeholder for address
                          // Add a dummy KTP image (simple base64 encoded 1x1 transparent pixel without data URI prefix)
                        $registration->ktp_image = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
                        
                        // Save the registration
                        $registration->save();
                        $success++;
                    }
                    
                } catch (\Exception $e) {
                    Log::error('CSV Import Error', [
                        'line' => $lineNumber,
                        'error' => $e->getMessage(),
                        'trace' => $e->getTraceAsString()
                    ]);
                    $errors[] = "Baris $lineNumber: Error sistem - " . $e->getMessage();
                    $failed++;
                }
            }
            fclose($handle);
        }
        
        // Return with results
        return back()->with([
            'import_results' => true,
            'success_count' => $success,
            'updated_count' => $updated,
            'error_count' => $failed,
            'import_errors' => $errors
        ]);
    }
}
