<?php

namespace App\Controllers;

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

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

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

    /**
     * Display the list of units
     *
     * @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');
        $status = $this->request->getGet('status');
        $page = $this->request->getGet('page') ?? 1;

        // Get units with pagination
        $perPage = 10;
        $units = $this->unitModel->getUnits($perPage, $search, $companyId, $status);

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

        return view('units/list', [
            'units' => $units,
            'pager' => $this->unitModel->pager,
            'search' => $search,
            'company_id' => $companyId,
            'status' => $status,
            'companies' => $companies,
            'title' => 'Units Management'
        ]);
    }

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

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

        $data['companies'] = $companies;
        $data['title'] = 'Add New Unit';

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

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

            // Get input data
            $unitData = [
                'company_id' => $this->request->getPost('company_id'),
                'unit_name' => $this->request->getPost('unit_name'),
                'unit_location' => $this->request->getPost('unit_location'),
                'unit_manager_name' => $this->request->getPost('unit_manager_name') ?? null,
                'unit_manager_number' => $this->request->getPost('unit_manager_number') ?? null,
                'unit_hr_name' => $this->request->getPost('unit_hr_name') ?? null,
                'unit_hr_number' => $this->request->getPost('unit_hr_number') ?? null,
                'total_workers' => $this->request->getPost('total_workers'),
                'contractual_workers' => $this->request->getPost('contractual_workers'),
                'status' => $this->request->getPost('status'),
            ];

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

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

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

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

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

        // Get input data
        $unitData = [
            'company_id' => $this->request->getPost('company_id'),
            'unit_name' => $this->request->getPost('unit_name'),
            'unit_location' => $this->request->getPost('unit_location'),
            'unit_manager_name' => $this->request->getPost('unit_manager_name') ?? null,
            'unit_manager_number' => $this->request->getPost('unit_manager_number') ?? null,
            'unit_hr_name' => $this->request->getPost('unit_hr_name') ?? null,
            'unit_hr_number' => $this->request->getPost('unit_hr_number') ?? null,
            'total_workers' => $this->request->getPost('total_workers'),
            'contractual_workers' => $this->request->getPost('contractual_workers'),
            'status' => $this->request->getPost('status'),
        ];

        // Save unit data
        if ($this->unitModel->save($unitData)) {
            session()->setFlashdata('success', 'Unit created successfully.');
            return redirect()->to('/units');
        } else {
            session()->setFlashdata('error', 'Failed to create unit.');
            return redirect()->back()->withInput();
        }
    }

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

        $unit = $this->unitModel->find($id);

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

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

        $data['unit'] = $unit;
        $data['companies'] = $companies;
        $data['title'] = 'Edit Unit';

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

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

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

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

            // Get input data
            $unitData = [
                'company_id' => $this->request->getPost('company_id'),
                'unit_name' => $this->request->getPost('unit_name'),
                'unit_location' => $this->request->getPost('unit_location'),
                'unit_manager_name' => $this->request->getPost('unit_manager_name') ?? null,
                'unit_manager_number' => $this->request->getPost('unit_manager_number') ?? null,
                'unit_hr_name' => $this->request->getPost('unit_hr_name') ?? null,
                'unit_hr_number' => $this->request->getPost('unit_hr_number') ?? null,
                'total_workers' => $this->request->getPost('total_workers'),
                'contractual_workers' => $this->request->getPost('contractual_workers'),
                'status' => $this->request->getPost('status'),
            ];

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

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

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

        $unit = $this->unitModel->find($id);

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

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

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

        // Get input data
        $unitData = [
            'company_id' => $this->request->getPost('company_id'),
            'unit_name' => $this->request->getPost('unit_name'),
            'unit_location' => $this->request->getPost('unit_location'),
            'unit_manager_name' => $this->request->getPost('unit_manager_name') ?? null,
            'unit_manager_number' => $this->request->getPost('unit_manager_number') ?? null,
            'unit_hr_name' => $this->request->getPost('unit_hr_name') ?? null,
            'unit_hr_number' => $this->request->getPost('unit_hr_number') ?? null,
            'total_workers' => $this->request->getPost('total_workers'),
            'contractual_workers' => $this->request->getPost('contractual_workers'),
            'status' => $this->request->getPost('status'),
        ];

        // Update unit data
        if ($this->unitModel->update($id, $unitData)) {
            session()->setFlashdata('success', 'Unit updated successfully.');
            return redirect()->to('/units');
        } else {
            session()->setFlashdata('error', 'Failed to update unit.');
            return redirect()->back()->withInput();
        }
    }

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

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

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

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

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

        $unit = $this->unitModel->find($id);

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

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

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

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

        $unit = $this->unitModel->find($id);

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

        // Get company details
        $company = $this->companyModel->find($unit['company_id']);

        $data['unit'] = $unit;
        $data['company'] = $company;
        $data['title'] = 'Unit Details';

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

    /**
     * Export units 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 units
        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');
        $status = $this->request->getGet('status');

        // Get units for export
        $units = $this->unitModel->getUnitsForExport($search, $companyId, $status);

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

        // Set headers for CSV download
        $filename = 'units_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 unit data
        $headers = [
            'ID',
            'Company Name',
            'Unit Name',
            'Unit Location',
            'Unit Manager Name',
            'Unit Manager Number',
            'Unit HR Name',
            'Unit HR Number',
            'Total Workers',
            'Contractual Workers',
            'Personnel Count',
            'Status',
            'Created At',
            'Updated At'
        ];
        fputcsv($fp, $headers);

        // Add unit data
        foreach ($units as $unit) {
            $row = [
                $unit['id'],
                $unit['company_name'],
                $unit['unit_name'],
                $unit['unit_location'],
                $unit['unit_manager_name'] ?? '',
                $unit['unit_manager_number'] ?? '',
                $unit['unit_hr_name'] ?? '',
                $unit['unit_hr_number'] ?? '',
                $unit['total_workers'],
                $unit['contractual_workers'],
                $unit['personnel_count'],
                $unit['status'],
                $unit['created_at'],
                $unit['updated_at']
            ];
            fputcsv($fp, $row);
        }

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

        foreach ($units as $unit) {
            foreach ($unit['personnel'] as $person) {
                $row = [
                    $unit['id'],
                    $unit['unit_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 units 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 units
        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');
        $status = $this->request->getGet('status');

        // Get units for export
        $units = $this->unitModel->getUnitsForExport($search, $companyId, $status);

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

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

        foreach ($units as $unit) {
            $html .= '
                    <tr>
                        <td>' . $unit['id'] . '</td>
                        <td>' . htmlspecialchars($unit['company_name']) . '</td>
                        <td>' . htmlspecialchars($unit['unit_name']) . '</td>
                        <td>' . htmlspecialchars($unit['unit_manager_name'] ?? '') . '</td>
                        <td>' . htmlspecialchars($unit['unit_hr_name'] ?? '') . '</td>
                        <td>' . $unit['total_workers'] . '</td>
                        <td>' . $unit['contractual_workers'] . '</td>
                        <td>' . $unit['personnel_count'] . '</td>
                        <td>' . $unit['status'] . '</td>
                        <td>' . $unit['created_at'] . '</td>
                    </tr>';
        }

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

        // Add personnel section
        $html .= '<div class="page-break"></div>';
        $html .= '<div class="section-title">Personnel Details</div>';
        $html .= '
            <table>
                <thead>
                    <tr>
                        <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 ($units as $unit) {
            foreach ($unit['personnel'] as $person) {
                $html .= '
                    <tr>
                        <td>' . htmlspecialchars($unit['unit_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 - Units 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 = 'units_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());
    }
}