<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\UnitModel;
use App\Models\PersonnelModel;
use CodeIgniter\HTTP\ResponseInterface;
use Dompdf\Dompdf;
use Dompdf\Options;

class Companies extends BaseController
{
    protected $companyModel;
    protected $unitModel;
    protected $personnelModel;

    public function __construct()
    {
        $this->companyModel = new CompanyModel();
        $this->unitModel = new UnitModel();
        $this->personnelModel = new PersonnelModel();
    }

    /**
     * Display the list of companies
     *
     * @return string
     */
    public function index()
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $area = $this->request->getGet('area');
        $status = $this->request->getGet('status');
        $page = $this->request->getGet('page') ?? 1;

        // Get companies with pagination
        $perPage = 10;
        $companies = $this->companyModel->getCompanies($perPage, $search, $area, $status);

        // Get areas for filter dropdown
        $areas = $this->companyModel->getAreas();

        // Get company statistics
        $stats = $this->companyModel->getCompanyStats();

        return view('companies/list', [
            'companies' => $companies,
            'pager' => $this->companyModel->pager,
            'search' => $search,
            'area' => $area,
            'status' => $status,
            'areas' => $areas,
            'stats' => $stats,
            'title' => 'Companies Management'
        ]);
    }

    /**
     * Show the form to create a new company
     *
     * @return string
     */
    public function create()
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can create companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        $data['areas'] = $this->companyModel->getAreas();
        $data['title'] = 'Add New Company';

        return view('companies/create', $data);
    }

    /**
     * Process the creation of a new company
     *
     * @return ResponseInterface
     */
    public function store()
    {
        // Check if this is an AJAX request
        if ($this->request->isAJAX()) {
            // Validate input
            if (!$this->validate($this->companyModel->validationRules, $this->companyModel->validationMessages)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $this->validator->getErrors()
                ]);
            }

            // Get input data
            $companyData = [
                'company_name' => $this->request->getPost('company_name'),
                'company_address' => $this->request->getPost('company_address'),
                'area' => $this->request->getPost('area'),
                'company_email' => $this->request->getPost('company_email'),
                'hr_name' => $this->request->getPost('hr_name') ?? null,
                'hr_number' => $this->request->getPost('hr_number') ?? null,
                'manager_name' => $this->request->getPost('manager_name') ?? null,
                'manager_number' => $this->request->getPost('manager_number') ?? null,
                'total_workers' => $this->request->getPost('total_workers'),
                'contractual_workers' => $this->request->getPost('contractual_workers'),
                'payroll' => $this->request->getPost('payroll') ?? null,
                'gst_tax_number' => $this->request->getPost('gst_tax_number') ?? null,
                'status' => $this->request->getPost('status'),
                'notes' => $this->request->getPost('notes') ?? null
            ];

            // Save company data
            if ($this->companyModel->save($companyData)) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Company created successfully.',
                    'data' => $this->companyModel->find($this->companyModel->getInsertID())
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Failed to create company.',
                    'errors' => $this->companyModel->errors()
                ]);
            }
        }

        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can create companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Validate input
        if (!$this->validate($this->companyModel->validationRules, $this->companyModel->validationMessages)) {
            return view('companies/create', [
                'validation' => $this->validator,
                'areas' => $this->companyModel->getAreas(),
                'title' => 'Add New Company'
            ]);
        }

        // Get input data
        $companyData = [
            'company_name' => $this->request->getPost('company_name'),
            'company_address' => $this->request->getPost('company_address'),
            'area' => $this->request->getPost('area'),
            'company_email' => $this->request->getPost('company_email'),
            'hr_name' => $this->request->getPost('hr_name') ?? null,
            'hr_number' => $this->request->getPost('hr_number') ?? null,
            'manager_name' => $this->request->getPost('manager_name') ?? null,
            'manager_number' => $this->request->getPost('manager_number') ?? null,
            'total_workers' => $this->request->getPost('total_workers'),
            'contractual_workers' => $this->request->getPost('contractual_workers'),
            'payroll' => $this->request->getPost('payroll') ?? null,
            'gst_tax_number' => $this->request->getPost('gst_tax_number') ?? null,
            'status' => $this->request->getPost('status'),
            'notes' => $this->request->getPost('notes') ?? null
        ];

        // Save company data
        if ($this->companyModel->save($companyData)) {
            session()->setFlashdata('success', 'Company created successfully.');
            return redirect()->to('/companies');
        } else {
            session()->setFlashdata('error', 'Failed to create company.');
            return redirect()->back()->withInput();
        }
    }

    /**
     * Show the form to edit a company
     *
     * @param int $id
     * @return string
     */
    public function edit($id)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can edit companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        $company = $this->companyModel->find($id);

        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        $data['company'] = $company;
        $data['areas'] = $this->companyModel->getAreas();
        $data['title'] = 'Edit Company';

        return view('companies/edit', $data);
    }

    /**
     * Process the update of a company
     *
     * @param int $id
     * @return ResponseInterface
     */
    public function update($id)
    {
        // Check if this is an AJAX request
        if ($this->request->isAJAX()) {
            $company = $this->companyModel->find($id);

            if (!$company) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Company not found'
                ]);
            }

            // Prepare validation rules with proper ID replacement for unique email check
            $validationRules = $this->companyModel->validationRules;
            
            // Specifically handle the company_email rule to exclude current record from unique check
            if (isset($validationRules['company_email'])) {
                // For updates, we need to exclude the current record from the unique check
                $validationRules['company_email'] = 'required|valid_email|is_unique[companies.company_email,id,' . $id . ']';
            }

            // Validate input
            if (!$this->validate($validationRules, $this->companyModel->validationMessages)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $this->validator->getErrors()
                ]);
            }

            // Get input data
            $companyData = [
                'company_name' => $this->request->getPost('company_name'),
                'company_address' => $this->request->getPost('company_address'),
                'area' => $this->request->getPost('area'),
                'company_email' => $this->request->getPost('company_email'),
                'hr_name' => $this->request->getPost('hr_name') ?? null,
                'hr_number' => $this->request->getPost('hr_number') ?? null,
                'manager_name' => $this->request->getPost('manager_name') ?? null,
                'manager_number' => $this->request->getPost('manager_number') ?? null,
                'total_workers' => $this->request->getPost('total_workers'),
                'contractual_workers' => $this->request->getPost('contractual_workers'),
                'payroll' => $this->request->getPost('payroll') ?? null,
                'gst_tax_number' => $this->request->getPost('gst_tax_number') ?? null,
                'status' => $this->request->getPost('status'),
                'notes' => $this->request->getPost('notes') ?? null
            ];

            // Update company data
            if ($this->companyModel->update($id, $companyData)) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Company updated successfully.',
                    'data' => $this->companyModel->find($id)
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Failed to update company.',
                    'errors' => $this->companyModel->errors()
                ]);
            }
        }

        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can update companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        $company = $this->companyModel->find($id);

        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Prepare validation rules with proper ID replacement for unique email check
        $validationRules = $this->companyModel->validationRules;
        
        // Specifically handle the company_email rule to exclude current record from unique check
        if (isset($validationRules['company_email'])) {
            // For updates, we need to exclude the current record from the unique check
            $validationRules['company_email'] = 'required|valid_email|is_unique[companies.company_email,id,' . $id . ']';
        }

        // Validate input
        if (!$this->validate($validationRules, $this->companyModel->validationMessages)) {
            return view('companies/edit', [
                'company' => $company,
                'validation' => $this->validator,
                'areas' => $this->companyModel->getAreas(),
                'title' => 'Edit Company'
            ]);
        }

        // Get input data
        $companyData = [
            'company_name' => $this->request->getPost('company_name'),
            'company_address' => $this->request->getPost('company_address'),
            'area' => $this->request->getPost('area'),
            'company_email' => $this->request->getPost('company_email'),
            'hr_name' => $this->request->getPost('hr_name') ?? null,
            'hr_number' => $this->request->getPost('hr_number') ?? null,
            'manager_name' => $this->request->getPost('manager_name') ?? null,
            'manager_number' => $this->request->getPost('manager_number') ?? null,
            'total_workers' => $this->request->getPost('total_workers'),
            'contractual_workers' => $this->request->getPost('contractual_workers'),
            'payroll' => $this->request->getPost('payroll') ?? null,
            'gst_tax_number' => $this->request->getPost('gst_tax_number') ?? null,
            'status' => $this->request->getPost('status'),
            'notes' => $this->request->getPost('notes') ?? null
        ];

        // Update company data
        if ($this->companyModel->update($id, $companyData)) {
            session()->setFlashdata('success', 'Company updated successfully.');
            return redirect()->to('/companies');
        } else {
            // Log the actual error for debugging
            log_message('error', 'Failed to update company ID: ' . $id . '. Data: ' . json_encode($companyData) . '. Errors: ' . json_encode($this->companyModel->errors()));
            session()->setFlashdata('error', 'Failed to update company.');
            return redirect()->back()->withInput();
        }
    }

    /**
     * Delete a company (soft delete by setting status to Inactive)
     *
     * @param int $id
     * @return ResponseInterface
     */
    public function delete($id)
    {
        // Check if this is an AJAX request
        if ($this->request->isAJAX()) {
            $company = $this->companyModel->find($id);

            if (!$company) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Company not found'
                ]);
            }

            // Soft delete by setting deleted_at timestamp
            if ($this->companyModel->delete($id)) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Company deleted successfully.'
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Failed to delete company.',
                    'errors' => $this->companyModel->errors()
                ]);
            }
        }

        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can delete companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        $company = $this->companyModel->find($id);

        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Soft delete by setting deleted_at timestamp
        if ($this->companyModel->delete($id)) {
            session()->setFlashdata('success', 'Company deleted successfully.');
        } else {
            session()->setFlashdata('error', 'Failed to delete company.');
        }

        return redirect()->to('/companies');
    }

    /**
     * View company details
     *
     * @param int $id
     * @return string
     */
    public function view($id)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        $company = $this->companyModel->find($id);

        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Get units for this company
        $units = $this->unitModel->getUnitsByCompany($id);
        
        // Get personnel for this company (using the general personnel model)
        $personnel = $this->personnelModel->getPersonnelByCompany($id);
        
        // Get contractors for this company
        $contractorModel = new \App\Models\ContractorModel();
        $contractors = $contractorModel->getContractorsByCompany($id);

        $data['company'] = $company;
        $data['units'] = $units;
        $data['personnel'] = $personnel;
        $data['contractors'] = $contractors;
        $data['title'] = 'Company Details';

        return view('companies/view', $data);
    }

    /**
     * Export companies as CSV with all related data
     *
     * @return ResponseInterface
     */
    public function exportCsv()
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can export companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $area = $this->request->getGet('area');
        $status = $this->request->getGet('status');

        // Get companies for export
        $companies = $this->companyModel->getCompaniesForExport($search, $area, $status);

        // Enhance companies data with units and personnel information
        foreach ($companies as &$company) {
            // Get units for this company
            $units = $this->unitModel->where('company_id', $company['id'])
                                    ->where('deleted_at', null)
                                    ->findAll();
            
            // Get personnel for this company
            $personnel = $this->personnelModel->where('company_id', $company['id'])
                                             ->where('deleted_at', null)
                                             ->findAll();
            
            // Add counts to company data
            $company['units_count'] = count($units);
            $company['personnel_count'] = count($personnel);
            
            // Store units and personnel data (for detailed export)
            $company['units'] = $units;
            $company['personnel'] = $personnel;
        }

        // Set headers for CSV download
        $filename = 'companies_detailed_' . date('Y-m-d_H-i-s') . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        // Create file pointer
        $fp = fopen('php://output', 'wb');

        // Add CSV headers for main company data
        $headers = [
            'ID',
            'Company Name',
            'Company Address',
            'Area',
            'Company Email',
            'HR Name',
            'HR Number',
            'Manager Name',
            'Manager Number',
            'Total Workers',
            'Contractual Workers',
            'Payroll',
            'GST/Tax Number',
            'Status',
            'Notes',
            'Units Count',
            'Personnel Count',
            'Created At',
            'Updated At'
        ];
        fputcsv($fp, $headers);

        // Add company data
        foreach ($companies as $company) {
            $row = [
                $company['id'],
                $company['company_name'],
                $company['company_address'],
                $company['area'],
                $company['company_email'],
                $company['hr_name'] ?? '',
                $company['hr_number'] ?? '',
                $company['manager_name'] ?? '',
                $company['manager_number'] ?? '',
                $company['total_workers'],
                $company['contractual_workers'],
                $company['payroll'] ?? '',
                $company['gst_tax_number'] ?? '',
                $company['status'],
                $company['notes'] ?? '',
                $company['units_count'],
                $company['personnel_count'],
                $company['created_at'],
                $company['updated_at']
            ];
            fputcsv($fp, $row);
        }

        // Add section for units
        fputcsv($fp, []); // Empty line
        fputcsv($fp, ['UNITS DATA']); // Section header
        fputcsv($fp, [
            'Company ID',
            'Company Name',
            'Unit ID',
            'Unit Name',
            'Unit Manager Name',
            'Unit Manager Email',
            'Unit Manager Phone',
            'Unit Address',
            'Status',
            'Created At'
        ]);

        foreach ($companies as $company) {
            foreach ($company['units'] as $unit) {
                $row = [
                    $company['id'],
                    $company['company_name'],
                    $unit['id'],
                    $unit['unit_name'],
                    $unit['unit_manager_name'] ?? '',
                    $unit['unit_manager_email'] ?? '',
                    $unit['unit_manager_phone'] ?? '',
                    $unit['unit_address'] ?? '',
                    $unit['status'],
                    $unit['created_at']
                ];
                fputcsv($fp, $row);
            }
        }

        // Add section for personnel
        fputcsv($fp, []); // Empty line
        fputcsv($fp, ['PERSONNEL DATA']); // Section header
        fputcsv($fp, [
            'Company ID',
            'Company Name',
            'Personnel ID',
            'Name',
            'Role',
            'Email',
            'Phone',
            'Address',
            'Status',
            'Created At'
        ]);

        foreach ($companies as $company) {
            foreach ($company['personnel'] as $person) {
                $row = [
                    $company['id'],
                    $company['company_name'],
                    $person['id'],
                    $person['name'],
                    $person['role'],
                    $person['email'] ?? '',
                    $person['phone'] ?? '',
                    $person['address'] ?? '',
                    $person['status'],
                    $person['created_at']
                ];
                fputcsv($fp, $row);
            }
        }

        // Close file pointer
        fclose($fp);

        // Exit to prevent additional output
        exit();
    }

    /**
     * Export companies as PDF with all related data
     *
     * @return ResponseInterface
     */
    public function exportPdf()
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        // Only admin and superadmin can export companies
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $area = $this->request->getGet('area');
        $status = $this->request->getGet('status');

        // Get companies for export
        $companies = $this->companyModel->getCompaniesForExport($search, $area, $status);

        // Enhance companies data with units and personnel information
        foreach ($companies as &$company) {
            // Get units for this company
            $units = $this->unitModel->where('company_id', $company['id'])
                                    ->where('deleted_at', null)
                                    ->findAll();
            
            // Get personnel for this company
            $personnel = $this->personnelModel->where('company_id', $company['id'])
                                             ->where('deleted_at', null)
                                             ->findAll();
            
            // Add counts to company data
            $company['units_count'] = count($units);
            $company['personnel_count'] = count($personnel);
            
            // Store units and personnel data
            $company['units'] = $units;
            $company['personnel'] = $personnel;
        }

        // Create HTML content for PDF
        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>Companies Detailed Report</title>
            <style>
                body { font-family: Arial, sans-serif; font-size: 12px; }
                table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
                th, td { border: 1px solid #ddd; padding: 6px; text-align: left; }
                th { background-color: #f2f2f2; font-size: 11px; }
                .header { text-align: center; margin-bottom: 20px; }
                .footer { text-align: center; margin-top: 20px; font-size: 10px; }
                .section-title { font-size: 14px; font-weight: bold; margin: 20px 0 10px 0; }
                .page-break { page-break-before: always; }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>Companies Detailed Report</h1>
                <p>Generated on: ' . date('Y-m-d H:i:s') . '</p>
            </div>
            
            <div class="section-title">Companies Summary</div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Company Name</th>
                        <th>Area</th>
                        <th>Company Email</th>
                        <th>HR Name</th>
                        <th>HR Number</th>
                        <th>Manager Name</th>
                        <th>Manager Number</th>
                        <th>Total Workers</th>
                        <th>Contractual</th>
                        <th>Payroll</th>
                        <th>Units</th>
                        <th>Personnel</th>
                        <th>Status</th>
                        <th>Created At</th>
                    </tr>
                </thead>
                <tbody>';

        foreach ($companies as $company) {
            $html .= '
                    <tr>
                        <td>' . $company['id'] . '</td>
                        <td>' . htmlspecialchars($company['company_name']) . '</td>
                        <td>' . $company['area'] . '</td>
                        <td>' . htmlspecialchars($company['company_email']) . '</td>
                        <td>' . htmlspecialchars($company['hr_name'] ?? '') . '</td>
                        <td>' . htmlspecialchars($company['hr_number'] ?? '') . '</td>
                        <td>' . htmlspecialchars($company['manager_name'] ?? '') . '</td>
                        <td>' . htmlspecialchars($company['manager_number'] ?? '') . '</td>
                        <td>' . $company['total_workers'] . '</td>
                        <td>' . $company['contractual_workers'] . '</td>
                        <td>' . ($company['payroll'] ?? '') . '</td>
                        <td>' . $company['units_count'] . '</td>
                        <td>' . $company['personnel_count'] . '</td>
                        <td>' . $company['status'] . '</td>
                        <td>' . $company['created_at'] . '</td>
                    </tr>';
        }

        $html .= '
                </tbody>
            </table>
            
            <div class="footer">
                <p>Total Companies: ' . count($companies) . '</p>
                <p>&copy; ' . date('Y') . ' Labourdnhdd CMS - Companies Management System</p>
            </div>';

        // Add units section
        $html .= '<div class="page-break"></div>';
        $html .= '<div class="section-title">Units Details</div>';
        $html .= '
            <table>
                <thead>
                    <tr>
                        <th>Company</th>
                        <th>Unit Name</th>
                        <th>Manager</th>
                        <th>Manager Email</th>
                        <th>Manager Phone</th>
                        <th>Status</th>
                        <th>Created At</th>
                    </tr>
                </thead>
                <tbody>';

        foreach ($companies as $company) {
            foreach ($company['units'] as $unit) {
                $html .= '
                    <tr>
                        <td>' . htmlspecialchars($company['company_name']) . '</td>
                        <td>' . htmlspecialchars($unit['unit_name']) . '</td>
                        <td>' . htmlspecialchars($unit['unit_manager_name'] ?? '') . '</td>
                        <td>' . htmlspecialchars($unit['unit_manager_email'] ?? '') . '</td>
                        <td>' . htmlspecialchars($unit['unit_manager_phone'] ?? '') . '</td>
                        <td>' . $unit['status'] . '</td>
                        <td>' . $unit['created_at'] . '</td>
                    </tr>';
            }
        }

        $html .= '
                </tbody>
            </table>';

        // Add personnel section
        $html .= '<div class="page-break"></div>';
        $html .= '<div class="section-title">Personnel Details</div>';
        $html .= '
            <table>
                <thead>
                    <tr>
                        <th>Company</th>
                        <th>Name</th>
                        <th>Role</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Created At</th>
                    </tr>
                </thead>
                <tbody>';

        foreach ($companies as $company) {
            foreach ($company['personnel'] as $person) {
                $html .= '
                    <tr>
                        <td>' . htmlspecialchars($company['company_name']) . '</td>
                        <td>' . htmlspecialchars($person['name']) . '</td>
                        <td>' . $person['role'] . '</td>
                        <td>' . htmlspecialchars($person['email'] ?? '') . '</td>
                        <td>' . htmlspecialchars($person['phone'] ?? '') . '</td>
                        <td>' . $person['status'] . '</td>
                        <td>' . $person['created_at'] . '</td>
                    </tr>';
            }
        }

        $html .= '
                </tbody>
            </table>
            
            <div class="footer">
                <p>Report generated on: ' . date('Y-m-d H:i:s') . '</p>
                <p>&copy; ' . date('Y') . ' Labourdnhdd CMS - Companies Management System</p>
            </div>
        </body>
        </html>';

        // Generate PDF using Dompdf
        $options = new Options();
        $options->set('defaultFont', 'Arial');
        $options->set('isRemoteEnabled', true);
        
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        // Set headers for PDF download
        $filename = 'companies_detailed_' . date('Y-m-d_H-i-s') . '.pdf';
        return $this->response
            ->setHeader('Content-Type', 'application/pdf')
            ->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
            ->setBody($dompdf->output());
    }
}