<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class JobCardMRController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        // Load model with proper name
        $this->load->model('Jobcardmr_model');
        $this->load->helper(['url', 'form']);
    }

    // -------------------------------------------------------
    // Default page
    // -------------------------------------------------------
    public function index()
    {
        $data = [
            'view' => 'JobCardMRSearch.php',
            'jobCardNo' => '',
            'jobCard' => null,
            'mrList' => [],
            'mrItems' => [],
            'searched' => false,
            'errorMsg' => '',
        ];

        $this->load->view('master', $data);
    }

    // -------------------------------------------------------
    // Search function
    // -------------------------------------------------------
    public function search()
    {
     
        $jobCardNo = trim($this->input->post('jobCardNo'));

        $jobCard = null;
        $mrList = [];
        $mrItems = [];
        $errorMsg = '';


        $data = [
            'view' => 'JobCardMRSearch.php',
            'jobCardNo' => $jobCardNo,
            'jobCard' => $jobCard,
            'mrList' => $mrList,
            'mrItems' => $mrItems,
            'searched' => true,
            'errorMsg' => $errorMsg,
        ];

        $this->load->view('master', $data);
    }

    // -------------------------------------------------------
    // Autocomplete
    // -------------------------------------------------------
    public function autocomplete()
    {
        $term = $this->input->get('term');

        $results = $this->Jobcardmr_model->searchJobCardNos($term ?? '');

        $output = [];

        foreach ($results as $row) {
            $output[] = [
                'id' => $row->id,
                'value' => $row->label,
                'label' => $row->label
            ];
        }

        header('Content-Type: application/json');
        echo json_encode($output);
        exit;
    }
}