<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imports\ClientInfoImport;
use Maatwebsite\Excel\Facades\Excel;
use Brian2694\Toastr\Facades\Toastr;

class ClientInfoImportController extends Controller
{
    /**
     * Show the import form
     */
    public function index()
    {
        if (auth()->user()->id != 1) {
            Toastr::error('You do not have permission to access this page', 'Error');
            return redirect()->back();
        }
        // Get all available columns from both tables
        $columns = $this->getAvailableColumns();

        return view('clients.clientInfoImport', compact('columns'));
    }

    /**
     * Process the import
     */
    public function import(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|file',
            'column_mapping' => 'required|string'
        ]);

        try {
            $columnMapping = $request->input('column_mapping');

            // Create import instance
            $import = new ClientInfoImport($columnMapping);

            // Process the import
            Excel::import($import, $request->file('excel_file'));

            // Get results
            $errors = $import->getErrors();
            $successCount = $import->getSuccessCount();

            // Prepare session data
            if (count($errors) > 0) {
                return redirect()->back()
                    ->with('showResults', true)
                    ->with('importErrors', $errors)
                    ->with('successCount', $successCount)
                    ->with('wasRolledBack', false);
            } else {
                Toastr::success("Successfully imported {$successCount} records", 'Success');
                return redirect()->back()
                    ->with('showResults', true)
                    ->with('successCount', $successCount)
                    ->with('importErrors', []);
            }

        } catch (\Exception $e) {
            Toastr::error('Import failed: ' . $e->getMessage(), 'Error');
            return redirect()->back();
        }
    }

    /**
     * Get available columns from both tables
     */
    protected function getAvailableColumns()
    {
        return [
            'Client Table' => [
                'pop_id' => 'POP ID (pop_id)',
                'billing_cycle' => 'Billing Cycle (billing_cycle)',
                'package_id' => 'Package ID (package_id)',
                'mac' => 'MAC Address (mac)',
                'password' => 'Password (password)',
                'ip_address' => 'IP Address (ip_address)',
                'expire_date' => 'Expire Date (expire_date)',
                'required_cable' => 'Required Cable (required_cable)',
                'client_approval' => 'Client Approval (client_approval)',
                'clients_status' => 'Client Status (clients_status)',
                'marketed_by' => 'Marketed By (marketed_by)',
                'sub_package_id' => 'Sub Package ID (sub_package_id)',
                'customer_code' => 'Customer Code (customer_code)',
                'payment_dadeline' => 'Payment Deadline (payment_dadeline)',
                'parmanent_discount' => 'Permanent Discount (parmanent_discount)',
            ],
            'Client Information Table' => [
                'clients_name' => 'Client Name (clients_name)',
                'father_name' => 'Father Name (father_name)',
                'mother_name' => 'Mother Name (mother_name)',
                'flat_no' => 'Flat No (flat_no)',
                'building_name' => 'Building Name (building_name)',
                'road_no' => 'Road No (road_no)',
                'block_sector' => 'Block/Sector (block_sector)',
                'area' => 'Area (area)',
                'district' => 'District (district)',
                'thana' => 'Thana (thana)',
                'contact_no' => 'Contact No (contact_no)',
                'national_id' => 'National ID (national_id)',
                'email' => 'Email (email)',
                'passport_no' => 'Passport No (passport_no)',
                'owner_name' => 'Owner Name (owner_name)',
                'owner_number' => 'Owner Number (owner_number)',
                'olt_pon' => 'OLT PON (olt_pon)',
                'otc' => 'OTC (otc)',
                'building_no' => 'Building No (building_no)',
                'remarks' => 'Remarks (remarks)',
                'dob' => 'Date of Birth (dob)',
                'cable_type' => 'Cable Type (cable_type)',
                'road_name' => 'Road Name (road_name)',
                'otc_due' => 'OTC Due (otc_due)',
                'other_contact' => 'Other Contact (other_contact)',
                'box' => 'Box (box)',
                'joinDate' => 'Join Date (joinDate)',
                'client_latitude' => 'Latitude (client_latitude)',
                'client_longitude' => 'Longitude (client_longitude)',
                'client_door' => 'Client Door (client_door)',
                'cat_type' => 'CAT Type (cat_type)',
                'cat_length' => 'CAT Length (cat_length)',
                'olt_no' => 'OLT No (olt_no)',
                'pon_port' => 'PON Port (pon_port)',
                'onu_serial' => 'ONU Serial (onu_serial)',
                'cable_id' => 'Cable ID (cable_id)',
                'customer_package_name' => 'Customer Package Name (customer_package_name)',
                'btrc_package_bandwidth' => 'BTRC Package Bandwidth (btrc_package_bandwidth)',
                'source_name' => 'Source Name (source_name)',
            ]
        ];
    }

    /**
     * Download sample Excel file
     */
    public function downloadSample()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="client_info_import_sample.csv"',
        ];

        $callback = function() {
            $file = fopen('php://output', 'w');

            // Add header row
            fputcsv($file, ['username', 'column_mapping']);

            // Add sample data rows
            fputcsv($file, ['user001', 'Sample Data 1']);
            fputcsv($file, ['user002', 'Sample Data 2']);
            fputcsv($file, ['user003', 'Sample Data 3']);

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
