<?php

namespace App\Controllers;

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

class Contractors extends BaseController
{
    protected $contractorModel;
    protected $companyModel;

    public function __construct()
    {
        $this->contractorModel = new ContractorModel();
        $this->companyModel = new CompanyModel();
    }

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

        // Get contractors with pagination
        $perPage = 10;
        $contractors = $this->contractorModel->getContractors($perPage, $search, $companyId);

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

        return view('contractors/list', [
            'contractors' => $contractors,
            'pager' => $this->contractorModel->pager,
            'search' => $search,
            'company_id' => $companyId,
            'companies' => $companies,
            'title' => 'Contractors Management'
        ]);
    }

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

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

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

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

    /**
     * Process the creation of a new contractor
     *
     * @return ResponseInterface
     */
    public function store()
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

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

        // Validate input
        if (!$this->validate($this->contractorModel->validationRules, $this->contractorModel->validationMessages)) {
            // Get companies for dropdown
            $companies = $this->companyModel->where('deleted_at', null)
                                           ->orderBy('company_name', 'ASC')
                                           ->findAll();

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

        // Get input data
        $contractorData = [
            'company_id' => $this->request->getPost('company_id'),
            'registration_number' => $this->request->getPost('registration_number') ?? null,
            'contractor_name' => $this->request->getPost('contractor_name'),
            'contractor_contact_no' => $this->request->getPost('contractor_contact_no') ?? null,
            'contractor_address' => $this->request->getPost('contractor_address') ?? null,
            'validity_date' => $this->request->getPost('validity_date') ?? null,
            'number_of_employees' => $this->request->getPost('number_of_employees') ?? 0,
            'sr_no_contractor' => $this->request->getPost('sr_no_contractor') ?? null,
            'nature_of_work' => $this->request->getPost('nature_of_work') ?? null,
            'no_of_contract_labours' => $this->request->getPost('no_of_contract_labours') ?? 0,
            'less_than_20' => $this->request->getPost('less_than_20') ?? 0,
            'twenty_and_above' => $this->request->getPost('twenty_and_above') ?? 0,
            'remarks' => $this->request->getPost('remarks') ?? null
        ];

        // Save contractor data
        if ($this->contractorModel->save($contractorData)) {
            session()->setFlashdata('success', 'Contractor created successfully.');
            return redirect()->to('/contractors');
        } else {
            session()->setFlashdata('error', 'Failed to create contractor.');
            return redirect()->back()->withInput();
        }
    }

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

        $contractor = $this->contractorModel->find($id);

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

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

        $data['contractor'] = $contractor;
        $data['companies'] = $companies;
        $data['title'] = 'Edit Contractor';

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

    /**
     * Process the update of a contractor
     *
     * @param int $id
     * @return ResponseInterface
     */
    public function update($id)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

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

        $contractor = $this->contractorModel->find($id);

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

        // Validate input
        if (!$this->validate($this->contractorModel->validationRules, $this->contractorModel->validationMessages)) {
            // Get companies for dropdown
            $companies = $this->companyModel->where('deleted_at', null)
                                           ->orderBy('company_name', 'ASC')
                                           ->findAll();

            return view('contractors/edit', [
                'contractor' => $contractor,
                'companies' => $companies,
                'validation' => $this->validator,
                'title' => 'Edit Contractor'
            ]);
        }

        // Get input data
        $contractorData = [
            'company_id' => $this->request->getPost('company_id'),
            'registration_number' => $this->request->getPost('registration_number') ?? null,
            'contractor_name' => $this->request->getPost('contractor_name'),
            'contractor_contact_no' => $this->request->getPost('contractor_contact_no') ?? null,
            'contractor_address' => $this->request->getPost('contractor_address') ?? null,
            'validity_date' => $this->request->getPost('validity_date') ?? null,
            'number_of_employees' => $this->request->getPost('number_of_employees') ?? 0,
            'sr_no_contractor' => $this->request->getPost('sr_no_contractor') ?? null,
            'nature_of_work' => $this->request->getPost('nature_of_work') ?? null,
            'no_of_contract_labours' => $this->request->getPost('no_of_contract_labours') ?? 0,
            'less_than_20' => $this->request->getPost('less_than_20') ?? 0,
            'twenty_and_above' => $this->request->getPost('twenty_and_above') ?? 0,
            'remarks' => $this->request->getPost('remarks') ?? null
        ];

        // Update contractor data
        if ($this->contractorModel->update($id, $contractorData)) {
            session()->setFlashdata('success', 'Contractor updated successfully.');
            return redirect()->to('/contractors');
        } else {
            session()->setFlashdata('error', 'Failed to update contractor.');
            return redirect()->back()->withInput();
        }
    }

    /**
     * Delete a contractor
     *
     * @param int $id
     * @return ResponseInterface
     */
    public function delete($id)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return redirect()->to('/login');
        }

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

        $contractor = $this->contractorModel->find($id);

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

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

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

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

        $contractor = $this->contractorModel->getContractorWithCompany($id);

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

        $data['contractor'] = $contractor;
        $data['title'] = 'Contractor Details';

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

    /**
     * Display contractors 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');
        }

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

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

        // Get contractors with pagination
        $perPage = 10;
        $contractors = $this->contractorModel->getContractors($perPage, $search, $companyId);

        return view('contractors/list_by_company', [
            'contractors' => $contractors,
            'pager' => $this->contractorModel->pager,
            'search' => $search,
            'company' => $company,
            'title' => 'Contractors for ' . $company['company_name']
        ]);
    }

    /**
     * Export contractors as CSV
     *
     * @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 contractors
        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');

        // Get all contractors for export (without pagination)
        $contractors = $this->contractorModel->getContractorsForExport($search, $companyId);

        // Set headers for CSV download
        $filename = 'contractors_' . 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 = [
            'Sr. No',
            'Registration Number',
            'Contractor Name',
            'Contractor Contact No',
            'Contractor Address',
            'Validity Date',
            'Number of Employees',
            'Sr. No. of Contractor',
            'Nature of Work',
            'No. of Contract Labours',
            'Less than 20',
            '20 and above',
            'Remarks',
            'Company Name',
            'Created At',
            'Updated At'
        ];
        fputcsv($fp, $headers);

        // Add contractor data
        $srNo = 1;
        foreach ($contractors as $contractor) {
            $row = [
                $srNo++,
                $contractor['registration_number'] ?? '',
                $contractor['contractor_name'],
                $contractor['contractor_contact_no'] ?? '',
                $contractor['contractor_address'] ?? '',
                $contractor['validity_date'] ?? '',
                $contractor['number_of_employees'],
                $contractor['sr_no_contractor'] ?? '',
                $contractor['nature_of_work'] ?? '',
                $contractor['no_of_contract_labours'],
                $contractor['less_than_20'],
                $contractor['twenty_and_above'],
                $contractor['remarks'] ?? '',
                $contractor['company_name'],
                $contractor['created_at'],
                $contractor['updated_at']
            ];
            fputcsv($fp, $row);
        }

        // Close file pointer
        fclose($fp);

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

    /**
     * Export contractors as PDF
     *
     * @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 contractors
        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');

        // Get all contractors for export (without pagination)
        $contractors = $this->contractorModel->getContractorsForExport($search, $companyId);

        // Create HTML content for PDF
        $html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>Contractors 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; }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>Contractors Report</h1>
                <p>Generated on: ' . date('Y-m-d H:i:s') . '</p>
            </div>
            
            <table>
                <thead>
                    <tr>
                        <th>Sr. No</th>
                        <th>Reg. No</th>
                        <th>Contractor Name</th>
                        <th>Contact No</th>
                        <th>Company</th>
                        <th>Validity Date</th>
                        <th>No. of Employees</th>
                        <th>Sr. No. Contractor</th>
                        <th>Nature of Work</th>
                        <th>Contract Labours</th>
                        <th>Less than 20</th>
                        <th>20 and above</th>
                    </tr>
                </thead>
                <tbody>';

        $srNo = 1;
        foreach ($contractors as $contractor) {
            $html .= '
                    <tr>
                        <td>' . $srNo++ . '</td>
                        <td>' . htmlspecialchars($contractor['registration_number'] ?? 'N/A') . '</td>
                        <td>' . htmlspecialchars($contractor['contractor_name']) . '</td>
                        <td>' . htmlspecialchars($contractor['contractor_contact_no'] ?? 'N/A') . '</td>
                        <td>' . htmlspecialchars($contractor['company_name']) . '</td>
                        <td>' . htmlspecialchars($contractor['validity_date'] ?? 'N/A') . '</td>
                        <td>' . htmlspecialchars($contractor['number_of_employees']) . '</td>
                        <td>' . htmlspecialchars($contractor['sr_no_contractor'] ?? 'N/A') . '</td>
                        <td>' . htmlspecialchars($contractor['nature_of_work'] ?? 'N/A') . '</td>
                        <td>' . htmlspecialchars($contractor['no_of_contract_labours']) . '</td>
                        <td>' . htmlspecialchars($contractor['less_than_20']) . '</td>
                        <td>' . htmlspecialchars($contractor['twenty_and_above']) . '</td>
                    </tr>';
        }

        $html .= '
                </tbody>
            </table>
            
            <div class="footer">
                <p>Total Contractors: ' . count($contractors) . '</p>
                <p>&copy; ' . date('Y') . ' Labourdnhdd CMS - Contractors 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', 'landscape');
        $dompdf->render();
        
        // Set headers for PDF download
        $filename = 'contractors_' . 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());
    }

    /**
     * Get company details for AJAX requests
     *
     * @param int $companyId
     * @return ResponseInterface
     */
    public function getCompanyDetails($companyId)
    {
        // Check user role for access control
        $role = session()->get('role');
        if (!$role) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unauthorized access'
            ]);
        }

        // Get company details
        $company = $this->companyModel->find($companyId);

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

        // Return company details
        return $this->response->setJSON([
            'status' => 'success',
            'data' => [
                'id' => $company['id'],
                'company_name' => $company['company_name'],
                'company_address' => $company['company_address'] ?? '',
                'company_email' => $company['company_email'] ?? '',
                'hr_name' => $company['hr_name'] ?? '',
                'hr_number' => $company['hr_number'] ?? '',
                'manager_name' => $company['manager_name'] ?? '',
                'manager_number' => $company['manager_number'] ?? '',
                'gst_tax_number' => $company['gst_tax_number'] ?? '',
                'total_workers' => $company['total_workers'] ?? 0,
                'contractual_workers' => $company['contractual_workers'] ?? 0,
                'payroll' => $company['payroll'] ?? '',
                'area' => $company['area'] ?? '',
                'status' => $company['status'] ?? '',
                'notes' => $company['notes'] ?? ''
            ]
        ]);
    }
}