<?php

namespace App\Http\Controllers;

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

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

    /**
     * Download the standard template CSV.
     */
    public function downloadTemplate(): StreamedResponse
    {
        $headers = [
            'name',
            'sku',
            'hs_code',
            'uom',
            'default_rate',
            'default_sale_type',
            'default_price_excl_st',
            'sro_schedule_no',
            'sro_item_serial_no'
        ];

        $sampleRow1 = [
            'Safety Helmet Premium',
            'SKU-HELM-001',
            '6506.1000',
            'PCS',
            '18%',
            'Goods at standard rate (default)',
            '1200.00',
            '',
            ''
        ];

        $sampleRow2 = [
            'Industrial Safety Gloves',
            'SKU-GLOV-002',
            '6116.1000',
            'PRS',
            '18%',
            'Goods at standard rate (default)',
            '350.00',
            '',
            ''
        ];

        return response()->streamDownload(function () use ($headers, $sampleRow1, $sampleRow2) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, $headers);
            fputcsv($handle, $sampleRow1);
            fputcsv($handle, $sampleRow2);
            fclose($handle);
        }, 'item_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.',
                'items' => []
            ]);
        }

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

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

        $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);

        $itemsPreview = [];
        foreach ($rows as $index => $row) {
            $name = trim($row['name'] ?? '');
            $sku = trim($row['sku'] ?? '');
            $hs = trim($row['hs_code'] ?? '');
            $uom = trim($row['uom'] ?? 'PCS');
            $rate = trim($row['default_rate'] ?? '18%');
            $saleType = trim($row['default_sale_type'] ?? 'Goods at standard rate (default)');
            $price = trim($row['default_price_excl_st'] ?? '0.00');
            $sroNo = trim($row['sro_schedule_no'] ?? '');
            $sroSerial = trim($row['sro_item_serial_no'] ?? '');

            $itemData = [
                'name' => $name,
                'sku' => $sku,
                'hs_code' => $hs,
                'uom' => $uom,
                'default_rate' => $rate,
                'default_sale_type' => $saleType,
                'default_price_excl_st' => $price,
                'sro_schedule_no' => $sroNo,
                'sro_item_serial_no' => $sroSerial,
                'errors' => []
            ];

            $validator = Validator::make($itemData, [
                'name' => 'required|string|max:150',
                'sku' => 'nullable|string|max:50',
                'hs_code' => 'nullable|string|max:20',
                'uom' => 'required|string|max:10',
                'default_rate' => 'required|string|max:20',
                'default_sale_type' => 'required|string|max:100',
                'default_price_excl_st' => 'required|numeric|min:0',
            ]);

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

            $itemsPreview[] = $itemData;
        }

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

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

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

        $importedCount = DB::transaction(function () use ($request, $businessId) {
            $count = 0;
            foreach ($request->input('items') as $data) {
                Item::create([
                    'business_id' => $businessId,
                    'name' => $data['name'],
                    'sku' => $data['sku'] ?: null,
                    'hs_code' => $data['hs_code'] ?: null,
                    'uom' => $data['uom'] ?: 'PCS',
                    'default_rate' => $data['default_rate'] ?: '18%',
                    'default_sale_type' => $data['default_sale_type'] ?: 'Goods at standard rate (default)',
                    'default_price_excl_st' => (float)$data['default_price_excl_st'],
                    'sro_schedule_no' => $data['sro_schedule_no'] ?: null,
                    'sro_item_serial_no' => $data['sro_item_serial_no'] ?: null,
                    'is_active' => true,
                ]);
                $count++;
            }
            return $count;
        });

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