<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Core\Company;
use App\Models\Core\FinancialSession;
use Illuminate\Http\Request;
use App\Services\CompanyService;
use App\Http\Requests\Admin\StoreCompanyRequest;
use App\Http\Requests\Admin\UpdateCompanyRequest;
use App\Http\Requests\Admin\ImportCompanyCsvRequest;

class CompanyController extends Controller
{
    protected $companyService;

    public function __construct(CompanyService $companyService)
    {
        $this->companyService = $companyService;
    }
    public function index(Request $request)
    {
        $this->authorize('viewAny', Company::class);

        $query = Company::query()
            ->with('financialSessions')
            ->withCount('financialSessions');

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('cin', 'like', "%{$search}%")
                    ->orWhere('pan', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $companies = $query->latest()->paginate(15);

        return view('admin.companies.index', compact('companies'));
    }

    public function create()
    {
        $this->authorize('create', Company::class);
        // Renamed variable to match user's blade template expectation
        $financialYears = FinancialSession::orderBy('name', 'desc')->get();
        return view('admin.companies.create', compact('financialYears'));
    }

    public function store(StoreCompanyRequest $request)
    {
        $this->companyService->createCompany($request->validated());

        return redirect()->route('admin.companies.index')
            ->with('success', 'Company created successfully.');
    }

    public function show(Company $company)
    {
        $company->load('financialSessions');
        return view('admin.companies.show', compact('company'));
    }

    public function edit(Company $company)
    {
        $this->authorize('update', $company);
        $financialYears = FinancialSession::orderBy('name', 'desc')->get();
        $company->load('financialSessions');
        return view('admin.companies.edit', compact('company', 'financialYears'));
    }

    public function update(UpdateCompanyRequest $request, Company $company)
    {
        $this->companyService->updateCompany($company, $request->validated());

        return redirect()->route('admin.companies.index')
            ->with('success', 'Company updated successfully.');
    }

    public function destroy(Company $company)
    {
        $this->authorize('delete', $company);
        $this->companyService->deleteCompany($company);

        return redirect()->route('admin.companies.index')
            ->with('success', 'Company deleted successfully.');
    }

    /**
     * Download a sample CSV file for company import
     */
    public function downloadSampleCsv()
    {
        $this->authorize('viewAny', Company::class);
        $filename = 'company_import_sample.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename={$filename}",
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0',
        ];

        $columns = [
            'Company Name',
            'CIN',
            'PAN',
            'TAN',
            'GSTIN',
            'Email',
            'Registered Office Address',
            'Date of Incorporation (YYYY-MM-DD)',
            'Financial Year ID'
        ];

        $sampleData = [];
        $fakerStates = ['Maharashtra', 'Delhi', 'Karnataka', 'Tamil Nadu', 'Gujarat'];

        for ($i = 1; $i <= 2; $i++) {
            $state = 'Delhi'; // Fixed for consistency with ADT-1 sample
            $code = 1000 + $i;

            // Standardized CIN for matching with ADT-1 Sample
            // e.g. U10001DL2021PTC100001
            $cin = 'U' . (10000 + $i) . 'DL202' . ($i % 5) . 'PTC' . (100000 + $i);

            $sampleData[] = [
                'Company ' . $i . ' Private Limited', // Name
                $cin, // CIN
                'ABCDE' . (1000 + $i) . 'F', // PAN
                'MUMB' . (10000 + $i) . 'C', // TAN
                '07ABCDE' . (1000 + $i) . 'F1Z5', // GSTIN (07 for Delhi)
                'contact' . $i . '@company' . $code . '.com', // Email
                $code . ', Industrial Area, New Delhi - 110001', // Address
                date('Y-m-d', strtotime("-{$i} weeks")), // Incorporation Date
                '1' // Financial Year ID
            ];
        }

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

            // Loop over sample data
            foreach ($sampleData as $row) {
                // Sanitize Formula Injection Risks
                $sanitizedRow = array_map(function ($field) {
                    if (is_string($field) && preg_match('/^[\=\+\-\@]/', $field)) {
                        return "'" . $field;
                    }
                    return $field;
                }, $row);
                fputcsv($file, $sanitizedRow);
            }
            fclose($file);
        };

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

    /**
     * Import companies from CSV file
     */
    /**
     * Import companies from CSV file
     */
    public function importCsv(ImportCompanyCsvRequest $request)
    {
        $file = $request->file('csv_file');
        $path = $file->getRealPath();

        try {
            $result = $this->companyService->importCompanies($path);

            if (!$result['success']) {
                return redirect()->route('admin.companies.index')
                    ->with('error', 'Import failed due to errors in the file. No data was imported.')
                    ->with('import_errors', $result['errors']);
            }

            $message = "Successfully imported {$result['imported']} companies.";
            return redirect()->route('admin.companies.index')
                ->with('success', $message);

        } catch (\Exception $e) {
            return redirect()->route('admin.companies.index')
                ->with('error', 'Import failed: ' . $e->getMessage());
        }
    }
}
