<?php

namespace App\Controllers;

use App\Models\MonthlyOutreachDataModel;
use CodeIgniter\Controller;

class ImportController extends BaseController
{
    public function index()
    {
        return view('import/monthly_outreach');
    }

    public function importCsv()
    {
        $response = [
            'success' => false,
            'message' => '',
            'imported' => 0,
            'failed' => 0,
            'errors' => []
        ];

        try {
            $validation = \Config\Services::validation();
            
            $validation->setRules([
                'csv_file' => [
                    'label' => 'CSV File',
                    'rules' => 'uploaded[csv_file]|ext_in[csv_file,csv]|max_size[csv_file,10240]'
                ]
            ]);

            if (!$validation->withRequest($this->request)->run()) {
                $response['message'] = 'Please upload a valid CSV file (max 10MB)';
                $response['errors'] = $validation->getErrors();
                return $this->response->setJSON($response);
            }

            $file = $this->request->getFile('csv_file');

            if (!$file->isValid()) {
                $response['message'] = 'Invalid file upload';
                return $this->response->setJSON($response);
            }

            // Read CSV file
            $csvData = array_map('str_getcsv', file($file->getTempName()));
            
            if (empty($csvData)) {
                $response['message'] = 'CSV file is empty';
                return $this->response->setJSON($response);
            }

            // Get headers from first row
            $headers = array_map('trim', $csvData[0]);
            unset($csvData[0]); // Remove header row

            $model = new MonthlyOutreachDataModel();
            $imported = 0;
            $failed = 0;
            $errors = [];

            foreach ($csvData as $rowIndex => $row) {
                // Skip empty rows
                if (empty(array_filter($row))) {
                    continue;
                }

                // Map CSV columns to database fields
                $data = [];
                foreach ($headers as $index => $header) {
                    $data[$header] = isset($row[$index]) ? trim($row[$index]) : '';
                }

                // Prepare data for insertion
                $insertData = [
                    'anganwadi_center_code' => $data['anganwadi_center_code'] ?? '',
                    'awc_worker_name' => $data['awc_worker_name'] ?? '',
                    'address_of_new_locations' => $data['address_of_new_locations'] ?? '',
                    'building_type' => $data['building_type'] ?? '',
                    'location_area' => $data['location_area'] ?? null,
                    'month_year' => $data['month_year'] ?? '',
                ];

                try {
                    if ($model->insert($insertData)) {
                        $imported++;
                    } else {
                        $failed++;
                        $errors[] = "Row " . ($rowIndex + 1) . ": " . implode(', ', $model->errors());
                    }
                } catch (\Exception $e) {
                    $failed++;
                    $errors[] = "Row " . ($rowIndex + 1) . ": " . $e->getMessage();
                }
            }

            $response['success'] = true;
            $response['message'] = "Import completed. Imported: {$imported}, Failed: {$failed}";
            $response['imported'] = $imported;
            $response['failed'] = $failed;
            $response['errors'] = $errors;

        } catch (\Exception $e) {
            $response['message'] = 'Error: ' . $e->getMessage();
        }

        return $this->response->setJSON($response);
    }

    public function downloadTemplate()
    {
        $headers = [
            'anganwadi_center_code',
            'awc_worker_name',
            'address_of_new_locations',
            'building_type',
            'location_area',
            'month_year'
        ];

        $filename = 'monthly_outreach_data_template.csv';
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, $headers);
        
        // Add a sample row
        $sampleData = [
            'AWC001',
            'John Doe',
            '123 Main Street',
            'Government Building',
            'Urban',
            '202510'
        ];
        fputcsv($output, $sampleData);
        
        fclose($output);
        exit;
    }
}
