<?php

namespace App\Controllers;

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

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

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

    /**
     * Display the list of personnel
     *
     * @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');
        $companyId = $this->request->getGet('company_id');
        $unitId = $this->request->getGet('unit_id');
        $roleFilter = $this->request->getGet('role');
        $status = $this->request->getGet('status');
        $page = $this->request->getGet('page') ?? 1;

        // Get personnel with pagination
        $perPage = 10;
        $personnel = $this->personnelModel->getPersonnel($perPage, $search, $companyId, $unitId, $roleFilter, $status);

        // Get companies and units for filter dropdowns
        $companies = $this->companyModel->where('deleted_at', null)->findAll();
        $units = $this->unitModel->where('deleted_at', null)->findAll();

        // Get personnel statistics
        $stats = $this->personnelModel->getPersonnelStats();

        return view('personnel/list', [
            'personnel' => $personnel,
            'pager' => $this->personnelModel->pager,
            'search' => $search,
            'company_id' => $companyId,
            'unit_id' => $unitId,
            'role' => $roleFilter,
            'status' => $status,
            'companies' => $companies,
            'units' => $units,
            'stats' => $stats,
            'title' => 'Personnel Management'
        ]);
    }

    /**
     * Display the list of personnel for a specific company
     *
     * @param int $companyId
     * @return string
     */
    public function indexByCompany($companyId)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

        $company = $this->companyModel->find($companyId);
        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $unitId = $this->request->getGet('unit_id');
        $roleFilter = $this->request->getGet('role');
        $status = $this->request->getGet('status');

        // Get personnel with pagination (filtered by company)
        $perPage = 10;
        $personnel = $this->personnelModel->getPersonnel($perPage, $search, $companyId, $unitId, $roleFilter, $status);

        // Get units for this company for filter dropdown
        $units = $this->unitModel->where('company_id', $companyId)->where('deleted_at', null)->findAll();

        // Get personnel statistics for this company
        $stats = $this->personnelModel->getPersonnelStats();

        return view('personnel/list', [
            'personnel' => $personnel,
            'pager' => $this->personnelModel->pager,
            'search' => $search,
            'company_id' => $companyId,
            'unit_id' => $unitId,
            'role' => $roleFilter,
            'status' => $status,
            'companies' => [$company], // Only this company
            'units' => $units,
            'stats' => $stats,
            'title' => 'Personnel Management for ' . $company['company_name'],
            'company' => $company // Pass the company object for context
        ]);
    }

    /**
     * Show the form to create a new personnel
     *
     * @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 personnel
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Get active companies and units
        $companies = $this->companyModel->where('status', 'Active')->where('deleted_at', null)->findAll();
        $units = $this->unitModel->where('status', 'Active')->where('deleted_at', null)->findAll();

        $data['companies'] = $companies;
        $data['units'] = $units;
        $data['title'] = 'Add New Personnel';

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

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

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

        $company = $this->companyModel->find($companyId);
        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Get active units for this company
        $units = $this->unitModel->where('company_id', $companyId)->where('status', 'Active')->where('deleted_at', null)->findAll();

        $data['company'] = $company;
        $data['units'] = $units;
        $data['title'] = 'Add New Personnel for ' . $company['company_name'];

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

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

            // Get input data
            $personnelData = [
                'company_id' => $this->request->getPost('company_id') ?: null,
                'unit_id' => $this->request->getPost('unit_id') ?: null,
                'name' => $this->request->getPost('name'),
                'role' => $this->request->getPost('role'),
                'email' => $this->request->getPost('email') ?? null,
                'phone' => $this->request->getPost('phone') ?? null,
                'address' => $this->request->getPost('address') ?? null,
                'status' => $this->request->getPost('status'),
            ];

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

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

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

        // Validate input
        if (!$this->validate($this->personnelModel->validationRules, $this->personnelModel->validationMessages)) {
            // Get active companies and units
            $companies = $this->companyModel->where('status', 'Active')->where('deleted_at', null)->findAll();
            $units = $this->unitModel->where('status', 'Active')->where('deleted_at', null)->findAll();

            return view('personnel/create', [
                'validation' => $this->validator,
                'companies' => $companies,
                'units' => $units,
                'title' => 'Add New Personnel'
            ]);
        }

        // Get input data
        $personnelData = [
            'company_id' => $this->request->getPost('company_id') ?: null,
            'unit_id' => $this->request->getPost('unit_id') ?: null,
            'name' => $this->request->getPost('name'),
            'role' => $this->request->getPost('role'),
            'email' => $this->request->getPost('email') ?? null,
            'phone' => $this->request->getPost('phone') ?? null,
            'address' => $this->request->getPost('address') ?? null,
            'status' => $this->request->getPost('status'),
        ];

        // Save personnel data
        if ($this->personnelModel->save($personnelData)) {
            session()->setFlashdata('success', 'Personnel created successfully.');
            return redirect()->to('/personnel');
        } else {
            session()->setFlashdata('error', 'Failed to create personnel.');
            return redirect()->back()->withInput();
        }
    }

    /**
     * Show the form to edit a personnel
     *
     * @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 personnel
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        $personnel = $this->personnelModel->find($id);

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

        // Get active companies and units
        $companies = $this->companyModel->where('status', 'Active')->where('deleted_at', null)->findAll();
        $units = $this->unitModel->where('status', 'Active')->where('deleted_at', null)->findAll();

        $data['personnel'] = $personnel;
        $data['companies'] = $companies;
        $data['units'] = $units;
        $data['title'] = 'Edit Personnel';

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

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

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

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

            // Get input data
            $personnelData = [
                'company_id' => $this->request->getPost('company_id') ?: null,
                'unit_id' => $this->request->getPost('unit_id') ?: null,
                'name' => $this->request->getPost('name'),
                'role' => $this->request->getPost('role'),
                'email' => $this->request->getPost('email') ?? null,
                'phone' => $this->request->getPost('phone') ?? null,
                'address' => $this->request->getPost('address') ?? null,
                'status' => $this->request->getPost('status'),
            ];

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

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

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

        $personnel = $this->personnelModel->find($id);

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

        // Validate input
        if (!$this->validate($this->personnelModel->validationRules, $this->personnelModel->validationMessages)) {
            // Get active companies and units
            $companies = $this->companyModel->where('status', 'Active')->where('deleted_at', null)->findAll();
            $units = $this->unitModel->where('status', 'Active')->where('deleted_at', null)->findAll();

            return view('personnel/edit', [
                'personnel' => $personnel,
                'validation' => $this->validator,
                'companies' => $companies,
                'units' => $units,
                'title' => 'Edit Personnel'
            ]);
        }

        // Get input data
        $personnelData = [
            'company_id' => $this->request->getPost('company_id') ?: null,
            'unit_id' => $this->request->getPost('unit_id') ?: null,
            'name' => $this->request->getPost('name'),
            'role' => $this->request->getPost('role'),
            'email' => $this->request->getPost('email') ?? null,
            'phone' => $this->request->getPost('phone') ?? null,
            'address' => $this->request->getPost('address') ?? null,
            'status' => $this->request->getPost('status'),
        ];

        // Update personnel data
        if ($this->personnelModel->update($id, $personnelData)) {
            session()->setFlashdata('success', 'Personnel updated successfully.');
            return redirect()->to('/personnel');
        } else {
            session()->setFlashdata('error', 'Failed to update personnel.');
            return redirect()->back()->withInput();
        }
    }

    /**
     * Delete a personnel (soft delete)
     *
     * @param int $id
     * @return ResponseInterface
     */
    public function delete($id)
    {
        // Check if this is an AJAX request
        if ($this->request->isAJAX()) {
            $personnel = $this->personnelModel->find($id);

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

            // Soft delete
            if ($this->personnelModel->delete($id)) {
                return $this->response->setJSON([
                    'status' => 'success',
                    'message' => 'Personnel deleted successfully.'
                ]);
            } else {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Failed to delete personnel.',
                    'errors' => $this->personnelModel->errors()
                ]);
            }
        }

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

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

        $personnel = $this->personnelModel->find($id);

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

        // Soft delete
        if ($this->personnelModel->delete($id)) {
            session()->setFlashdata('success', 'Personnel deleted successfully.');
        } else {
            session()->setFlashdata('error', 'Failed to delete personnel.');
        }

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

    /**
     * View personnel 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');
        }

        $personnel = $this->personnelModel->find($id);

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

        // Get company and unit details if they exist
        $company = null;
        $unit = null;
        
        if ($personnel['company_id']) {
            $company = $this->companyModel->find($personnel['company_id']);
        }
        
        if ($personnel['unit_id']) {
            $unit = $this->unitModel->find($personnel['unit_id']);
        }

        $data['personnel'] = $personnel;
        $data['company'] = $company;
        $data['unit'] = $unit;
        $data['title'] = 'Personnel Details';

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

    /**
     * Export personnel as CSV with detailed information
     *
     * @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 personnel
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $companyId = $this->request->getGet('company_id');
        $unitId = $this->request->getGet('unit_id');
        $roleFilter = $this->request->getGet('role');
        $status = $this->request->getGet('status');

        // Get personnel for export
        $personnel = $this->personnelModel->getPersonnelForExport($search, $companyId, $unitId, $roleFilter, $status);

        // Set headers for CSV download
        $filename = 'personnel_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
        $headers = [
            'ID',
            'Company Name',
            'Unit Name',
            'Name',
            'Role',
            'Email',
            'Phone',
            'Address',
            'Status',
            'Created At',
            'Updated At'
        ];
        fputcsv($fp, $headers);

        // Add personnel data
        foreach ($personnel as $p) {
            $row = [
                $p['id'],
                $p['company_name'] ?? '',
                $p['unit_name'] ?? '',
                $p['name'],
                $p['role'],
                $p['email'] ?? '',
                $p['phone'] ?? '',
                $p['address'] ?? '',
                $p['status'],
                $p['created_at'],
                $p['updated_at']
            ];
            fputcsv($fp, $row);
        }

        // Close file pointer
        fclose($fp);

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

    /**
     * Export personnel as PDF with detailed information
     *
     * @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 personnel
        if (!in_array($role, ['admin', 'superadmin'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Access denied');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $companyId = $this->request->getGet('company_id');
        $unitId = $this->request->getGet('unit_id');
        $roleFilter = $this->request->getGet('role');
        $status = $this->request->getGet('status');

        // Get personnel for export
        $personnel = $this->personnelModel->getPersonnelForExport($search, $companyId, $unitId, $roleFilter, $status);

        // Create HTML content for PDF
        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>Personnel 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>Personnel Detailed Report</h1>
                <p>Generated on: ' . date('Y-m-d H:i:s') . '</p>
            </div>
            
            <div class="section-title">Personnel Summary</div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Company</th>
                        <th>Unit</th>
                        <th>Name</th>
                        <th>Role</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Created At</th>
                    </tr>
                </thead>
                <tbody>';

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

        $html .= '
                </tbody>
            </table>
            
            <div class="footer">
                <p>Total Personnel: ' . count($personnel) . '</p>
                <p>&copy; ' . date('Y') . ' Labourdnhdd CMS - Personnel 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 = 'personnel_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());
    }

    /**
     * Export personnel as CSV for a specific company with detailed information
     *
     * @param int $companyId
     * @return ResponseInterface
     */
    public function exportCsvByCompany($companyId)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

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

        $company = $this->companyModel->find($companyId);
        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $unitId = $this->request->getGet('unit_id');
        $roleFilter = $this->request->getGet('role');
        $status = $this->request->getGet('status');

        // Get personnel for export (filtered by company)
        $personnel = $this->personnelModel->getPersonnelForExport($search, $companyId, $unitId, $roleFilter, $status);

        // Set headers for CSV download
        $filename = 'personnel_' . $company['company_name'] . '_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
        $headers = [
            'ID',
            'Unit Name',
            'Name',
            'Role',
            'Email',
            'Phone',
            'Address',
            'Status',
            'Created At',
            'Updated At'
        ];
        fputcsv($fp, $headers);

        // Add personnel data
        foreach ($personnel as $p) {
            $row = [
                $p['id'],
                $p['unit_name'] ?? '',
                $p['name'],
                $p['role'],
                $p['email'] ?? '',
                $p['phone'] ?? '',
                $p['address'] ?? '',
                $p['status'],
                $p['created_at'],
                $p['updated_at']
            ];
            fputcsv($fp, $row);
        }

        // Close file pointer
        fclose($fp);

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

    /**
     * Export personnel as PDF for a specific company with detailed information
     *
     * @param int $companyId
     * @return ResponseInterface
     */
    public function exportPdfByCompany($companyId)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

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

        $company = $this->companyModel->find($companyId);
        if (!$company) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Company not found');
        }

        // Get filter parameters
        $search = $this->request->getGet('search');
        $unitId = $this->request->getGet('unit_id');
        $roleFilter = $this->request->getGet('role');
        $status = $this->request->getGet('status');

        // Get personnel for export (filtered by company)
        $personnel = $this->personnelModel->getPersonnelForExport($search, $companyId, $unitId, $roleFilter, $status);

        // Create HTML content for PDF
        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>Personnel Detailed Report for ' . htmlspecialchars($company['company_name']) . '</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; }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>Personnel Detailed Report for ' . htmlspecialchars($company['company_name']) . '</h1>
                <p>Generated on: ' . date('Y-m-d H:i:s') . '</p>
            </div>
            
            <div class="section-title">Personnel Summary</div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Unit</th>
                        <th>Name</th>
                        <th>Role</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Created At</th>
                    </tr>
                </thead>
                <tbody>';

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

        $html .= '
                </tbody>
            </table>
            
            <div class="footer">
                <p>Total Personnel: ' . count($personnel) . '</p>
                <p>&copy; ' . date('Y') . ' Labourdnhdd CMS - Personnel 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 = 'personnel_' . $company['company_name'] . '_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());
    }
}