<?php

namespace App\Http\Controllers;

use App\Models\Business;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\StreamedResponse;

class CustomerImportController extends Controller
{
    /**
     * Display the import page UI.
     */
    public function show()
    {
        return view('customers.import');
    }

    /**
     * Download the standard template CSV.
     */
    public function downloadTemplate(): StreamedResponse
    {
        $headers = [
            'name',
            'ntn_cnic',
            'registration_type',
            'province',
            'address',
            'phone',
            'email'
        ];

        $sampleRow1 = [
            'Ali Ahmed Trading',
            '4210112345679',
            'Registered',
            'Sindh',
            'Shop 12, Plaza A, Karachi',
            '03001234567',
            'ali@trading.com'
        ];

        $sampleRow2 = [
            'Walk-in Client',
            '',
            'Unregistered',
            'Punjab',
            'Model Town, Lahore',
            '',
            ''
        ];

        return response()->streamDownload(function () use ($headers, $sampleRow1, $sampleRow2) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, $headers);
            fputcsv($handle, $sampleRow1);
            fputcsv($handle, $sampleRow2);
            fclose($handle);
        }, 'customer_import_template.csv', [
            'Content-Type' => 'text/csv',
        ]);
    }

    /**
     * Process upload for preview.
     */
    public function preview(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:csv,txt|max:4096'
        ]);

        $file = $request->file('file');
        $filePath = $file->getRealPath();

        if (!file_exists($filePath) || !is_readable($filePath)) {
            return response()->json([
                'success' => false,
                'error' => 'Unable to read upload file.',
                'customers' => []
            ]);
        }

        $handle = fopen($filePath, 'r');
        if (!$handle) {
            return response()->json([
                'success' => false,
                'error' => 'Unable to open file stream.',
                'customers' => []
            ]);
        }

        $headers = fgetcsv($handle);
        if (!$headers) {
            fclose($handle);
            return response()->json([
                'success' => false,
                'error' => 'Empty CSV file uploaded.',
                'customers' => []
            ]);
        }

        $headerMap = array_map(function($h) {
            return str_replace([' ', '-'], '_', strtolower(trim($h)));
        }, $headers);

        $rows = [];
        $line = 1;
        while (($row = fgetcsv($handle)) !== false) {
            $line++;
            if (count($row) !== count($headerMap)) {
                continue;
            }
            $rows[] = array_combine($headerMap, $row);
        }
        fclose($handle);

        $customersPreview = [];
        foreach ($rows as $index => $row) {
            $name = trim($row['name'] ?? '');
            $ntn = preg_replace('/[^0-9]/', '', trim($row['ntn_cnic'] ?? ''));
            $regType = trim($row['registration_type'] ?? '');
            if (empty($regType)) {
                $regType = !empty($ntn) ? 'Registered' : 'Unregistered';
            }
            $province = trim($row['province'] ?? 'Sindh');
            $address = trim($row['address'] ?? '');
            $phone = trim($row['phone'] ?? '');
            $email = trim($row['email'] ?? '');

            $customerData = [
                'name' => $name,
                'ntn_cnic' => $ntn,
                'registration_type' => $regType,
                'province' => $province,
                'address' => $address,
                'phone' => $phone,
                'email' => $email,
                'errors' => []
            ];

            $validator = Validator::make($customerData, [
                'name' => 'required|string|max:150',
                'ntn_cnic' => 'nullable|string|max:20',
                'registration_type' => 'required|string|in:Registered,Unregistered',
                'province' => 'required|string|in:Sindh,Punjab,KPK,Balochistan,Islamabad',
                'email' => 'nullable|email|max:100',
                'phone' => 'nullable|string|max:30',
            ]);

            if ($validator->fails()) {
                $customerData['errors'] = $validator->errors()->all();
            }

            $customersPreview[] = $customerData;
        }

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

    /**
     * Save the validated customers to DB.
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'customers' => 'required|array',
            'customers.*.name' => 'required|string|max:150',
            'customers.*.province' => 'required|string',
        ]);

        $businessId = Business::currentId() ?? 1;

        $importedCount = DB::transaction(function () use ($request, $businessId) {
            $count = 0;
            foreach ($request->input('customers') as $data) {
                Customer::create([
                    'business_id' => $businessId,
                    'name' => $data['name'],
                    'ntn_cnic' => $data['ntn_cnic'] ?: 'Unregistered',
                    'registration_type' => $data['registration_type'] ?: 'Unregistered',
                    'province' => $data['province'],
                    'address' => $data['address'] ?: 'Imported Buyer Address',
                    'phone' => $data['phone'] ?: null,
                    'email' => $data['email'] ?: null,
                    'is_active' => true,
                ]);
                $count++;
            }
            return $count;
        });

        return response()->json([
            'success' => true,
            'message' => "Successfully imported {$importedCount} customers."
        ]);
    }
}
