<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// CNJ_AUTOCADASTRO_VERSION: 2025-06-24_v4

class cases extends MX_Controller {

	public function __construct()
	{
		parent::__construct();
		
		//$this->auth->check_access('1', true);
		
		$this->load->model("cases_model");
		$this->load->model("tax_model");
		$this->load->model("location_model");
		$this->load->model("case_stage_model");
		$this->load->model("custom_field_model");
		
	}
	
	
	function index(){
		
		$data['cases'] = $this->cases_model->get_all();
		$data['courts'] = $this->cases_model->get_all_courts();
		$data['clients'] = $this->cases_model->get_all_clients();
		$data['locations'] = $this->location_model->get_all();
		$data['stages'] = $this->case_stage_model->get_all();
		$data['page_title'] = lang('case');
		$data['body'] = 'case/list';
		$this->load->view('template/main', $data);	
	}
	
	
	
	function get_case_by_client(){
		$cases = $this->cases_model->get_cases_by_client_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                        <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}
	
	function get_case_by_client_starred(){
		$cases = $this->cases_model->get_cases_by_client_id_starred($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                        <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}	
	
	
	
	function get_case_by_court(){
		$cases = $this->cases_model->get_cases_by_court_id($_POST['id']);
	
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}

	function get_case_by_court_starred(){
		$cases = $this->cases_model->get_cases_by_court_id_starred($_POST['id']);
	
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}

	

	function get_case_by_location(){
		$cases = $this->cases_model->get_cases_by_location_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}

	function get_case_by_location_starred(){
		$cases = $this->cases_model->get_cases_by_location_id_starred($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}


	function get_case_by_case_stage_id(){
		$cases = $this->cases_model->get_cases_by_case_stage_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}

	function get_case_by_case_stage_id_starred(){
		$cases = $this->cases_model->get_cases_by_case_stage_id_starred($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}


	function get_case_by_case_filing_date(){
		$cases = $this->cases_model->get_cases_by_filing_date($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                    	 echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
						echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}

	function get_case_by_case_filing_date_starred(){
		$cases = $this->cases_model->get_cases_by_filing_date_starred($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                   ';
				   		if(isset($cases)):
                    	 echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                   <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
						echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}


	function get_case_by_case_hearing_date(){
		$cases = $this->cases_model->get_cases_by_hearing_date($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}

	function get_case_by_case_hearing_date_starred(){
		$cases = $this->cases_model->get_cases_by_hearing_date_starred($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('client').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				   		if(isset($cases)):
                     echo '   
						<tbody>
                            ';
							 $i=1;foreach ($cases as $new){
							 
							 echo '
                                <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
									
								'; if($new->is_starred==0){ 
								echo '
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
								echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>
								';
									}
									
								echo'	</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									
                                    <td width="47%">
										<a class="btn btn-default"  href="'.site_url('admin/cases/view_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										<a class="btn btn-info"  href="'.site_url('admin/cases/fees/'.$new->id).'"><i class="fa fa-inr"></i> '.lang('fees').'</a>	
                                      	<a class="btn btn-success"  href="'.site_url('admin/cases/dates/'.$new->id).'"><i class="fa fa-calendar"></i> '.lang('hearing_date').'</a>							
                                        <a class="btn btn-primary"  href="'.site_url('admin/cases/edit/'.$new->id) .'"><i class="fa fa-edit"></i> '.lang('edit').'</a>
										<a class="btn btn-warning"  href="'.site_url('admin/cases/archived/'.$new->id).'"><i class="fa fa-close"></i> '.lang('archived').'</a>
                                    </td>
                                </tr>
							';	
                              $i++;}
					echo '		  
                        </tbody>';
                        endif;
                    
				echo '</table>';
					
		
	}


	
	function view_all(){
		$data['cases'] = $this->cases_model->get_case_by_date();
		$ids='';
		foreach($data['cases'] as $ind => $key){
		
			$ids[]=$key->case_id;
		}
		
		$this->cases_model->cases_view_by_admin($ids);
		$data['page_title'] =  lang('view_all') . lang('cases');
		$data['body'] = 'case/view_all';
		$this->load->view('template/main', $data);	

	}	
	
	function get_court_categories()
	{
		$data['case_categories'] 	= $this->cases_model->get_all_case_categories();
		$result = $this->cases_model->get_court_catogries_by_location($_POST['id']);

		echo '
		<select name="court_category_id" id="court_category_id" class="chzn col-md-12" >
										<option value="">--Select Court Category--</option>
									';
									foreach($result as $new) {
											$sel = "";
											if(set_select('court_category_id', $new->id)) $sel = "selected='selected'";
											echo '<option value="'.$new->id.'" '.$sel.'>'.$new->name.'</option>';
										}
										
		echo'</select>';						
	}
	
	function get_courts()
	{
		$courts = $this->cases_model->get_all_courts();
		$result = $this->cases_model->get_court_by_location_c_category($_POST['l_id'],$_POST['c_id']);
		echo '
		<select name="court_id" id="court_id" class="chzn col-md-12" >
										<option value="">--Select Court Category--</option>
									';
									foreach($result as $new) {
											$sel = "";
											if(set_select('court_id', $new->id)) $sel = "selected='selected'";
											echo '<option value="'.$new->id.'" '.$sel.'>'.$new->name.'</option>';
										}
										
		echo'</select>';						
	}
	
	
	function starred_cases(){
		$data['cases'] = $this->cases_model->get_all_starred();
		$data['courts'] = $this->cases_model->get_all_courts();
		$data['clients'] = $this->cases_model->get_all_clients();
		$data['locations'] = $this->location_model->get_all();
		$data['stages'] = $this->case_stage_model->get_all();
		$data['page_title'] = lang('case');
		$data['body'] = 'case/starred_list';
		$this->load->view('template/main', $data);	

	}	
	
	
	
	function archived_cases(){
		$data['cases'] = $this->cases_model->get_all_archived();
		$data['courts'] = $this->cases_model->get_all_courts();
		$data['clients'] = $this->cases_model->get_all_clients();
		$data['locations'] = $this->location_model->get_all();
		$data['stages'] = $this->case_stage_model->get_all();
		$data['page_title'] = lang('archived_cases');
		$data['body'] = 'case/archive_list';
		$this->load->view('template/main', $data);	
	}	
	
	function get_archive_case_by_client(){
		$cases = $this->cases_model->get_archive_cases_by_client_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                        <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('clients').'</th>
								<th>'.lang('case').' '.lang('stage').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				    if(isset($cases)):
				echo '	
                        <tbody>
                            '. $i=1;foreach ($cases as $new){
                  echo '              <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
							';		
									if($new->is_starred==0){ 
						echo '			
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
							echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>';
								}
							echo '
									</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									<td>'.$new->stage.'</td>
									
                                    <td width="20%">
									 	 <a class="btn btn-primary"  href="'.site_url('admin/cases/view_archived_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										 <a class="btn btn-danger" style="margin-left:20px;" href="'.site_url('admin/cases/restore/'.$new->id).'" onclick="return areyousure()"><i class="fa fa-check"></i> '.lang('restore').'</a>
                                    </td>
                                </tr>';
								 $i++;}
                       echo ' </tbody>';
                         endif;
                   echo ' </table>
					';
	}	
	
	
	function get_archive_case_by_court(){
		$cases = $this->cases_model->get_archive_cases_by_court_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('clients').'</th>
								<th>'.lang('case').' '.lang('stage').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				    if(isset($cases)):
				echo '	
                        <tbody>
                            '. $i=1;foreach ($cases as $new){
                  echo '              <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
							';		
									if($new->is_starred==0){ 
						echo '			
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
							echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>';
								}
							echo '
									</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									<td>'.$new->stage.'</td>
									
                                     <td width="20%">
									 	 <a class="btn btn-primary"  href="'.site_url('admin/cases/view_archived_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										 <a class="btn btn-danger" style="margin-left:20px;" href="'.site_url('admin/cases/restore/'.$new->id).'" onclick="return areyousure()"><i class="fa fa-check"></i> '.lang('restore').'</a>
                                    </td>
                                </tr>';
								 $i++;}
                       echo ' </tbody>';
                         endif;
                   echo ' </table>
					';
	}	
	
	
	function get_archive_case_by_location(){
		$cases = $this->cases_model->get_archive_cases_by_location_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('clients').'</th>
								<th>'.lang('case').' '.lang('stage').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				    if(isset($cases)):
				echo '	
                        <tbody>
                            '. $i=1;foreach ($cases as $new){
                echo '              <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
							';		
									if($new->is_starred==0){ 
				echo '			
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
				echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>';
								}
				echo '
									</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									<td>'.$new->stage.'</td>
									
                                    <td width="20%">
									 	 <a class="btn btn-primary"  href="'.site_url('admin/cases/view_archived_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										 <a class="btn btn-danger" style="margin-left:20px;" href="'.site_url('admin/cases/restore/'.$new->id).'" onclick="return areyousure()"><i class="fa fa-check"></i> '.lang('restore').'</a>
                                    </td>
                                </tr>';
								 $i++;}
                echo ' </tbody>';
                         endif;
                echo ' </table>
					';
	}	
	
	
	function get_archive_case_by_case_stage_id(){
		$cases = $this->cases_model->get_archive_cases_by_case_stage_id($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                         <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('clients').'</th>
								<th>'.lang('case').' '.lang('stage').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				    if(isset($cases)):
				echo '	
                        <tbody>
                            '. $i=1;foreach ($cases as $new){
                echo '              <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
							';		
									if($new->is_starred==0){ 
				echo '			
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
				echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>';
								}
				echo '
									</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									<td>'.$new->stage.'</td>
									
                                     <td width="20%">
									 	 <a class="btn btn-primary"  href="'.site_url('admin/cases/view_archived_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										 <a class="btn btn-danger" style="margin-left:20px;" href="'.site_url('admin/cases/restore/'.$new->id).'" onclick="return areyousure()"><i class="fa fa-check"></i> '.lang('restore').'</a>
                                    </td>
                                </tr>';
								 $i++;}
                echo ' </tbody>';
                         endif;
                echo ' </table>
					';
	}	
	
	
	function get_archive_case_by_case_filing_date(){
		$cases = $this->cases_model->get_archive_cases_by_filing_date($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                        <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('clients').'</th>
								<th>'.lang('case').' '.lang('stage').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                   ';
				    if(isset($cases)):
				echo '	
                        <tbody>
                            '. $i=1;foreach ($cases as $new){
                echo '              <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
							';		
									if($new->is_starred==0){ 
				echo '			
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
				echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>';
								}
				echo '
									</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									<td>'.$new->stage.'</td>
									
                                     <td width="20%">
									 	 <a class="btn btn-primary"  href="'.site_url('admin/cases/view_archived_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										 <a class="btn btn-danger" style="margin-left:20px;" href="'.site_url('admin/cases/restore/'.$new->id).'" onclick="return areyousure()"><i class="fa fa-check"></i> '.lang('restore').'</a>
                                    </td>
                                </tr>';
								 $i++;}
                echo ' </tbody>';
                         endif;
                echo ' </table>
					';
	}	
	
	
	function get_archive_case_by_case_hearing_date(){
			$cases = $this->cases_model->get_archive_cases_by_hearing_date($_POST['id']);
		echo '
		<table id="example1" class="table table-bordered table-striped table-mailbox">
                        <thead>
                            <tr>
                                <th width="5%">'.lang('serial_number').'</th>
								<th width="8%">'.lang('star').'</th>
								<th>'.lang('case').' '.lang('title').'</th>
								<th>'.lang('case').' '.lang('number').'</th>
								<th>'.lang('clients').'</th>
								<th>'.lang('case').' '.lang('stage').'</th>
								<th width="20%">'.lang('action').'</th>
                            </tr>
                        </thead>
                        
                   ';
				    if(isset($cases)):
				echo '	
                        <tbody>
                            '. $i=1;foreach ($cases as $new){
                echo '              <tr class="gc_row">
                                    <td>'.$i.'</td>
									
									<td class="small-col">
							';		
									if($new->is_starred==0){ 
				echo '			
									<a href="" at="90" class="Privat"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star-o"></i></a>
								';
									}else{
				echo '
									<a href="" at="90" class="Public"><span style="display:none">'.$new->id.'</span>
									<i class="fa fa-star"></i></a>';
								}
				echo '
									</td>
                                    <td>'.$new->title.'</td>
								    <td>'.$new->case_no.'</td>
									<td>'.$new->client.'</td>
									<td>'.$new->stage.'</td>
									
                                     <td width="20%">
									 	 <a class="btn btn-primary"  href="'.site_url('admin/cases/view_archived_case/'.$new->id).'"><i class="fa fa-eye"></i> '.lang('view').'</a>
										 <a class="btn btn-danger" style="margin-left:20px;" href="'.site_url('admin/cases/restore/'.$new->id).'" onclick="return areyousure()"><i class="fa fa-check"></i> '.lang('restore').'</a>
                                    </td>
                                </tr>';
								 $i++;}
                echo ' </tbody>';
                         endif;
                echo ' </table>
					';
	}
	
	
	
	function restore($id)
	{
		$this->cases_model->restore_case($id);
		$this->session->set_flashdata('message', lang('case_has_been_restored'));
		redirect('admin/cases');
	}
	
	
	
	function archived($id=false){
	
		$data['clients']		 	= $this->cases_model->get_all_clients();
		$data['id']					=$id;
		$data['case']				= $this->cases_model->get_case_by_id($id);
		
		
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('notes', 'lang:notes', 'required');
			$this->form_validation->set_rules('close_date', 'lang:date', 'trim|required');
			 
			if ($this->form_validation->run()==true)
            {
				$save['notes'] = $this->input->post('notes');
				$save['close_date'] = $this->input->post('close_date');
				$save['case_id'] = $id;
				$this->cases_model->save_archived($save);
				$this->cases_model->set_is_archived($id);
              	$this->session->set_flashdata('message', lang('case_is_archived'));
				redirect('admin/cases/archived_cases');
			}
		}		
	
		$data['page_title'] = lang('archive') . lang('case');
		$data['body'] = 'case/archive';
		$this->load->view('template/main', $data);	
	}
	

	function view_archived_case($id=false){
		$data['clients']		 	= $this->cases_model->get_all_clients();
		$data['stages'] 			= $this->case_stage_model->get_all();
		$data['acts']			 	= $this->cases_model->get_all_acts();
		$data['courts']			 	= $this->cases_model->get_all_courts();
		$data['locations']		 	= $this->cases_model->get_all_locations();
		$data['case_categories'] 	= $this->cases_model->get_all_case_categories();
		$data['court_categories']	= $this->cases_model->get_all_court_categories();
		$data['id'] 				= $id;
		$data['payment_modes']		= $this->cases_model->get_all_payment_modes();
		$data['fees_all']			= $this->cases_model->get_fees_all($id);
		$data['case']				= $this->cases_model->get_archive_case_by_id($id);
		$data['cases']		 		= $this->cases_model->get_all_extended_case_by_id($id);
		$data['cases']		 		= $this->cases_model->get_all_extended_case_by_id($id);
		$data['page_title'] 		= lang('view') . lang('archived_case');
		$data['body'] 				= 'case/view_archived';
	
		$this->load->view('template/main', $data);	
	}
	
	function view_case($id=false){
		$data['fields'] = $this->custom_field_model->get_custom_fields(2);	
		$data['clients']		 	= $this->cases_model->get_all_clients();
		$data['stages']				= $this->case_stage_model->get_all();
		$data['acts']			 	= $this->cases_model->get_all_acts();
		$data['courts']			 	= $this->cases_model->get_all_courts();
		$data['locations']		 	= $this->cases_model->get_all_locations();
		$data['case_categories'] 	= $this->cases_model->get_all_case_categories();
		$data['court_categories']	= $this->cases_model->get_all_court_categories();
		$data['id'] 				= $id;
		$data['payment_modes']		= $this->cases_model->get_all_payment_modes();
		$data['fees_all']			= $this->cases_model->get_fees_all($id);
		$data['case']				= $this->cases_model->get_archive_case_by_id($id);
		$data['cases']		 		= $this->cases_model->get_all_extended_case_by_id($id);
		$data['cases']		 		= $this->cases_model->get_all_extended_case_by_id($id);
		
		$this->cases_model->case_view_by_admin($id);
		
		$data['page_title']			= lang('view') . lang('case');
		$data['body'] 				= 'case/view_case';
		$this->load->view('template/main', $data);	
	}
	
	function add(){
		$data['fields_clients'] = $this->custom_field_model->get_custom_fields(1);
		$data['fields']			 = $this->custom_field_model->get_custom_fields(2);
		$data['clients']		 = $this->cases_model->get_all_clients();
		$data['stages'] 		 = $this->case_stage_model->get_all();
		$data['acts'] 			 = $this->cases_model->get_all_acts();
		$data['courts']			 = $this->cases_model->get_all_courts();
		$data['locations'] 		 = $this->cases_model->get_all_locations();
		$data['case_categories'] = $this->cases_model->get_all_case_categories();
		$data['court_categories']= $this->cases_model->get_all_court_categories();
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_message('required', lang('custom_required'));
			$this->form_validation->set_rules('title', 'lang:title', 'required');
			$this->form_validation->set_rules('client_id', 'Client', 'required');
			$this->form_validation->set_rules('case_no', 'Case No', 'trim|required|is_unique[cases.case_no]');
			$this->form_validation->set_rules('location_id', 'Location', 'required');
			$this->form_validation->set_rules('case_stage_id', 'Case Stage', 'required');
			$this->form_validation->set_rules('court_id', 'Court', 'required');
			$this->form_validation->set_rules('court_category_id', 'Court Category', 'required');
			$this->form_validation->set_rules('case_category_id', 'Case Category', 'required');
			$this->form_validation->set_rules('act_id', 'Act', 'required');
			$this->form_validation->set_rules('start_date', 'Filing Date', 'required');
			$this->form_validation->set_rules('description', 'Description', '');
			$this->form_validation->set_rules('fees', 'Fees', '');
			$this->form_validation->set_rules('o_lawyer', 'Opposite Lawyer', '');
			$this->form_validation->set_rules('hearing_date', 'Description', '');
			 
			if ($this->form_validation->run()==true)
            {
				$save['title'] = $this->input->post('title');
				$save['case_no'] = $this->input->post('case_no');
				$save['client_id'] = $this->input->post('client_id');
				$save['location_id'] = $this->input->post('location_id');
				$save['court_id'] = $this->input->post('court_id');
				$save['court_category_id'] = $this->input->post('court_category_id');
				$save['case_stage_id'] = $this->input->post('case_stage_id');
				$save['case_category_id'] = json_encode($this->input->post('case_category_id'));
				$save['act_id'] = json_encode($this->input->post('act_id'));
				$save['description'] = $this->input->post('description');
				$save['start_date'] = $this->input->post('start_date');
				$save['hearing_date'] = $this->input->post('hearing_date');
				$save['o_lawyer'] = $this->input->post('o_lawyer');
				$save['fees'] = $this->input->post('fees');
             
			 	$p_key = $this->cases_model->save($save);
				$reply = $this->input->post('reply');
					if(!empty($reply)){
					foreach((array)$this->input->post('reply') as $key => $val) {
						$save_fields[] = array(
							'custom_field_id'=> $key,
							'reply'=> $val,
							'table_id'=> $p_key,
							'form'=> 2,
						);	
					
					}	
					$this->custom_field_model->save_answer($save_fields);
				}
                $this->session->set_flashdata('message', lang('case_created'));
				redirect('admin/cases');
				
			}
		}		
		
		
		$data['page_title'] = lang('add') . lang('case');
		$data['body'] = 'case/add';
		
		
		$this->load->view('template/main', $data);	

	}	
	
	
	function edit($id=false){
	
		$data['clients']		 	= $this->cases_model->get_all_clients();
		$data['stages'] 			= $this->case_stage_model->get_all();
		$data['acts']			 	= $this->cases_model->get_all_acts();
		$data['courts']			 	= $this->cases_model->get_all_courts();
		$data['locations']		 	= $this->cases_model->get_all_locations();
		$data['case_categories'] 	= $this->cases_model->get_all_case_categories();
		$data['court_categories']	= $this->cases_model->get_all_court_categories();
		$data['id']					=	$id;
		$data['case'] 				= $this->cases_model->get_case_by_id($id);
		$data['fields'] 			= $this->custom_field_model->get_custom_fields(2);	
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('client_id', 'lang:client', 'required');
			$this->form_validation->set_rules('case_no', 'lang:case_number', 'trim|required');
			$this->form_validation->set_rules('location_id', 'lang:location', 'required');
			$this->form_validation->set_rules('court_id', 'lang:court', 'required');
			$this->form_validation->set_rules('court_category_id', 'lang:court_category', 'required');
			$this->form_validation->set_rules('case_category_id', 'lang:case_category', 'required');
			$this->form_validation->set_rules('act_id', 'lang:act', 'required');
			$this->form_validation->set_rules('start_date', 'lang:filing_date', 'required');
			 $this->form_validation->set_message('required', lang('custom_required'));
			if ($this->form_validation->run()==true)
            {
				$save['title'] = $this->input->post('title');
				$save['case_no'] = $this->input->post('case_no');
				$save['client_id'] = $this->input->post('client_id');
				$save['location_id'] = $this->input->post('location_id');
				$save['court_id'] = $this->input->post('court_id');
				$save['court_category_id'] = $this->input->post('court_category_id');
				$save['case_stage_id'] = $this->input->post('case_stage_id');
				$save['case_category_id'] = json_encode($this->input->post('case_category_id'));
				$save['act_id'] = json_encode($this->input->post('act_id'));
				$save['description'] = $this->input->post('description');
				$save['start_date'] = $this->input->post('start_date');
				$save['hearing_date'] = $this->input->post('hearing_date');
				$save['o_lawyer'] = $this->input->post('o_lawyer');
				$save['fees'] = $this->input->post('fees');
				
				$reply = $this->input->post('reply');
				if(!empty($reply)){	
					foreach((array)$this->input->post('reply') as $key => $val) {
						$save_fields[] = array(
							'custom_field_id'=> $key,
							'reply'=> $val,
							'table_id'=> $id,
							'form'=> 2,
						);	
					
					}	
					$this->custom_field_model->delete_answer($id,$form=2);
					$this->custom_field_model->save_answer($save_fields);
				}
				$this->cases_model->update($save,$id);
              	$this->session->set_flashdata('message',  lang('case_created'));
				redirect('admin/cases');
			}
		}		
	
		$data['page_title'] = lang('edit') . lang('court');
		$data['body'] = 'case/edit';
		$this->load->view('template/main', $data);	

	}
	
	function notes($id=false){
		$data['id']					=	$id;
		$data['case'] 				= $this->cases_model->get_case_by_id($id);
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('notes', 'lang:notes', 'required');
			 $this->form_validation->set_message('required', lang('custom_required'));
			if ($this->form_validation->run()==true)
            {
				$save['notes'] = $this->input->post('notes');
				
				$this->cases_model->update($save,$id);
              	$this->session->set_flashdata('message',  lang('notes_saved'));
				redirect('admin/cases/notes/'.$id);
			}
		}		
	
		$data['page_title'] =  lang('notes');
		$data['body'] = 'case/notes';
		$this->load->view('template/main', $data);	

	}
	
	
	
	function dates($id=false){
	
		$data['cases']		 	= $this->cases_model->get_all_extended_case_by_id($id);
		$data['id'] =$id;
		$data['case']				= $this->cases_model->get_case_by_id($id);
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('date', 'lang:date', 'required');
			$this->form_validation->set_message('required', lang('custom_required'));
			 
			if ($this->form_validation->run()==true)
            {
			
				if($_FILES['img'] ['name'] !='')
					{ 
						
					
						$config['upload_path'] = './assets/uploads/files/';
						$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
						$config['max_size']	= '10000';
						$config['max_width']  = '10000';
						$config['max_height']  = '6000';
				
						$this->load->library('upload', $config);
				
						if ( !$img = $this->upload->do_upload('img'))
							{
								
							}
							else
							{
								$img_data = array('upload_data' => $this->upload->data());
							}
						$save['document'] = $img_data['upload_data']['file_name'];
					}
					
				$save['case_id'] = $id;	
				$save['next_date'] = $this->input->post('date');
				$save['last_date'] = $this->input->post('date2');
				$save['note'] = $this->input->post('notes');
				$this->cases_model->save_extended_case($save);
              	$this->session->set_flashdata('message', 'Extended Date Saved');
				redirect('admin/cases/dates/'.$id);
				
			}
		}		
	
		
		$data['body'] = 'case/extended_dates';
		$this->load->view('template/main', $data);	

	}
	
	
	function dates_detail($id=false){
	
		$data['cases']		 	= $this->cases_model->get_extended_case_by_id($id);
		$data['id'] 			= $id;
		$data['case']			= $this->cases_model->get_case_by_id($id);
		$data['body'] 			= 'case/extended_dates_detail';
		$this->load->view('template/main', $data);	

	}	
	
	function fees($id){
		$data['tax']			= $this->tax_model->get_all();
		$data['payment_modes']			= $this->cases_model->get_all_payment_modes();
		$data['receipts']			= $this->cases_model->get_receipts($id);
		$data['case']					= $this->cases_model->get_case_by_id($id);
		$data['fees_all']				= $this->cases_model->get_fees_all($id);
		$data['id'] 					= $id;
		$invoice			= $this->cases_model->get_invoice_number();
		
		//echo '<pre>'; print_r($data['receipts']);die;

		if(empty($invoice->invoice)){
			$data['invoice_no'] = $this->settings->invoice_no;
		}else{
			$data['invoice_no'] = $invoice->invoice+1;
		}
		
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('amount', 'lang:amount', 'required');
			$this->form_validation->set_rules('payment_mode_id', 'lang:payment_mode', 'required');
			$this->form_validation->set_rules('date', 'lang:date', 'required');
			$this->form_validation->set_rules('invoice_no', 'lang:invoice', 'required');
			if ($this->form_validation->run()==true)
            {
			
				$save['amount'] = $this->input->post('amount');
				$save['total'] = $this->input->post('total');
				$save['payment_mode_id'] = $this->input->post('payment_mode_id');
				$save['case_id'] = $id;
				$save['date'] = $this->input->post('date');
				$save['invoice'] =  $data['invoice_no'];
				
				$fees_id = $this->cases_model->save_fees($save);
				$save_tax=array();
				$taxes = $this->input->post('tax_id');
				if(!empty($taxes)){
				$i=1;
					foreach($taxes as $new){
						$save_tax[$i]['tax_id'] = $new;
						$save_tax[$i]['fees_id'] = $fees_id;
					$i++;
					}
				$this->cases_model->save_taxes($save_tax);
				}
				
				
				
              	$this->session->set_flashdata('message', lang('fees_updated'));
				redirect('admin/cases/fees/'.$id);
			}
		}
		$data['body'] = 'case/fees';
		$this->load->view('template/main', $data);
	}
	
	function view_receipt($id){
		$data['receipt']			= $this->cases_model->get_receipt($id);
		//echo '<pre>'; print_r($data['receipt']);die;
		$data['payment_modes']			= $this->cases_model->get_all_payment_modes();
		$data['setting']     = $this->settings;
		$data['body'] = 'case/view_receipt';
		$this->load->view('template/main', $data);
	}
	
	function print_receipt($id){
		$data['receipt']			= $this->cases_model->get_receipt($id);
		//echo '<pre>'; print_r($data['receipt']);die;
		$data['payment_modes']			= $this->cases_model->get_all_payment_modes();
		$data['setting']     = $this->settings;
		//$data['body'] = '';
		$this->load->view('case/print_receipt', $data);
	}
	
	function pdf($id=false){
		$this->load->helper('dompdf_helper');
		$this->load->helper('download');
		$data['receipt']			= $this->cases_model->get_receipt($id);
		$data['payment_modes']			= $this->cases_model->get_all_payment_modes();
		$data['setting']     = $this->settings;
		$data['page_title'] = lang('receipt');
		//$data['body'] = 'invoice/pdf';
		$html = $this->load->view('case/pdf_receipt', $data,true);		
		pdf_create($html, 'Receipt_'.$data['receipt']->id);
		

	}	
	
	
	
	public function mail($id=false)
	{ 
		$data['receipt']			= $this->cases_model->get_receipt($id);
		$data['payment_modes']			= $this->cases_model->get_all_payment_modes();
		$data['setting']     = $this->settings;
		$data['page_title'] = lang('receipt');
		
		///echo $data['receipt']->u_email;die;
		if(!empty($data['setting']->image)){ 
 			$img = '<img src="'.site_url('assets/uploads/images/'.$data['setting']->image).'"  height="70" width="80"  style="padding-left:30px;" />';
 		}
		$html = $this->load->view('case/pdf_receipt', $data,true);			
		$message = $html;
		$msg 				 = html_entity_decode($message,ENT_QUOTES, 'UTF-8');
		$params['recipient'] = $data['receipt']->u_email;;
		$params['subject'] 	 = "Receipt";
		$params['message']   = $msg;
		modules::run('admin/fomailer/send_email',$params);
	
		$this->session->set_flashdata('message', lang('receipt_send'));
		redirect('admin/cases/fees/'.$data['receipt']->case_id);
			
	/*
		$this->load->library('email');
		$this->load->helper('string');    
		/*$config = array(
				'protocol' => "smtp",
				'smtp_host' => "ssl://smtp.gmail.com",
				'smtp_port' => "465",
				'smtp_user' => "",
				'smtp_pass' => "",
				'charset' => "utf-8",
				'mailtype' => "html",
				'newline' => "\r\n"
			);
		$config['mailtype'] = 'html';
		$config['charset'] = 'utf-8';
		

        $this->load->library('email', $config);
			
		$this->email->initialize($config);
		
													
			
			//echo '<pre>';print_r($message);exit;
			$this->email->from($data['setting']->email,'Invoice');
			
			$email = $data['details']->email;
			$this->email->to($email);
			$this->email->subject('Invoice');
			$this->email->message(html_entity_decode($message,ENT_QUOTES, 'UTF-8'));
			$sent = $this->email->send();
			*/
			//echo 'Mail Sent to '.$email;exit;
	}
	
	
	function receipt($id){
		$data['tax']			= $this->tax_model->get_all();
		$data['payment_modes']			= $this->cases_model->get_all_payment_modes();
		$data['case']					= $this->cases_model->get_case_by_id($id);
		$data['fees_all']				= $this->cases_model->get_fees_all($id);
		$data['id'] 					= $id;
		$invoice			= $this->cases_model->get_invoice_number();
		
		if ($this->input->server('REQUEST_METHOD') === 'POST')
        {	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('r_amount', 'lang:amount', '');
			if ($this->form_validation->run()==true)
            {
			//echo '<pre>'; print_r($_POST);die;
			
				$save['amount'] = $this->input->post('r_amount');
				$save['date'] = $this->input->post('r_date');
				$save['fees_id'] = $this->input->post('fees_id');
				$save['case_id'] = $this->input->post('case_id');
				
				$this->cases_model->save_receipt($save);
				
				
				
				
              	$this->session->set_flashdata('message', lang('receipt_created'));
				redirect('admin/cases/fees/'.$id);
			}
		}
		$data['body'] = 'case/fees';
		$this->load->view('template/main', $data);
	}
	
	function delete($id=false){
		
		if($id){
			$this->cases_model->delete($id);
			redirect('admin/cases');
			$this->session->set_flashdata('message',  lang('case_deleted'));
		}
	}
	
	function delete_archive_case($id=false){
		
		if($id){
			$this->cases_model->delete($id);
			redirect('admin/cases/archived_cases');
			$this->session->set_flashdata('message',  lang('case_deleted'));
		}
	}	
	
	function delete_fees($id=false){
		
		if($id){
			$this->cases_model->delete_fees($id);
			$this->session->set_flashdata('message', lang('fees_deleted'));
			redirect('admin/cases');
			
		}
	}	
	
	function delete_deceipt($id=0, $c_id=null){
		//$rc = $this->cases_model->get_receipt($id);
		if($id){
			$this->cases_model->delete_receipt($id);
			$this->session->set_flashdata('message', lang('receipt_deleted'));
			redirect('admin/cases/fees/'.$c_id);
			
		}
	}	
	
	
		
	function delete_history($id=false){
		
		if($id){
			$this->cases_model->delete_history($id);
			$this->session->set_flashdata('message', lang('history_deleted'));
			redirect('admin/cases');
		}
	}	

		
	function set_starred()
	{
		 $this->cases_model->set_is_starred($_POST['id']);
	}	
	
	function update_set_starred()
	{
		 $this->cases_model->update_set_is_starred($_POST['id']);
	}	
	
		
	


	// ============================================================
	// CNJ AUTO-CADASTRO – métodos adicionados automaticamente
	// ============================================================

	// Diagnóstico: acesse admin/cases/debug_datajud/NUMERO_CNJ para ver resposta bruta
	function debug_datajud($numero = '') {
		if (empty($numero)) die('Informe o número: admin/cases/debug_datajud/0000000-00.0000.0.00.0000');

		$numero    = urldecode($numero);
		$info      = $this->_parse_numero_cnj($numero);
		$tribunal  = $info['tribunal'] ?? 'não identificado';
		$indice    = strtolower($tribunal);
		$setting   = $this->db->select('datajud_api_key')->get('settings')->row();
		$api_key   = trim($setting->datajud_api_key ?? '');
		$endpoint  = 'https://api-publica.datajud.cnj.jus.br/api_publica_' . $indice . '/_search';

		$queries = [
			'term_keyword'  => json_encode(['query' => ['term'         => ['numeroProcesso.keyword' => $numero]]]),
			'match_phrase'  => json_encode(['query' => ['match_phrase' => ['numeroProcesso' => $numero]]]),
			'match_simples' => json_encode(['query' => ['match'        => ['numeroProcesso' => $numero]]]),
		];

		$resultados = [];
		foreach ($queries as $tipo => $payload) {
			$ch = curl_init($endpoint);
			curl_setopt_array($ch, [
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_TIMEOUT        => 30,
				CURLOPT_CONNECTTIMEOUT => 10,
				CURLOPT_POST           => true,
				CURLOPT_POSTFIELDS     => $payload,
				CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: APIKey ' . $api_key],
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_SSL_VERIFYHOST => false,
				CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; LawSystem/1.0)',
				CURLOPT_FOLLOWLOCATION => true,
			]);
			$resp = curl_exec($ch);
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);
			$resultados[$tipo] = ['http' => $code, 'response' => json_decode($resp, true)];
		}

		header('Content-Type: application/json; charset=utf-8');
		echo json_encode([
			'numero'   => $numero,
			'tribunal' => $tribunal,
			'indice'   => $indice,
			'endpoint' => $endpoint,
			'api_key_primeiros_10' => substr($api_key, 0, 10) . '...',
			'resultados' => $resultados,
		], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
	}

	function buscar_processo_cnj() {
		header('Content-Type: application/json; charset=utf-8');

		$numero = trim($this->input->post('numero_cnj'));

		if (empty($numero)) {
			echo json_encode(['success' => false, 'msg' => 'Número CNJ não informado.']);
			return;
		}

		$numero_limpo = preg_replace('/[^0-9\-\.]/', '', $numero);
		$info_cnj = $this->_parse_numero_cnj($numero_limpo);
		$resultado = $this->_consultar_datajud($numero_limpo, $info_cnj);

		if (!$resultado['success'] && defined('WORKER_URL')) {
			$resultado = $this->_consultar_worker_pje($numero_limpo);
		}

		echo json_encode($resultado);
	}


	function importar_processo_cnj() {
		header('Content-Type: application/json; charset=utf-8');

		$numero       = trim($this->input->post('case_no'));
		$titulo       = trim($this->input->post('title'));
		$cliente      = (int) $this->input->post('client_id');
		$tribunal     = trim($this->input->post('tribunal_nome'));
		$data_inicio  = trim($this->input->post('start_date'));
		$descricao    = trim($this->input->post('description'));
		$polo_passivo = trim($this->input->post('o_lawyer'));

		if (empty($numero) || empty($titulo) || $cliente <= 0) {
			echo json_encode(['success' => false, 'msg' => 'Campos obrigatórios ausentes.']);
			return;
		}

		$existe = $this->db->where('case_no', $numero)->count_all_results('cases');
		if ($existe > 0) {
			echo json_encode(['success' => false, 'msg' => 'Processo já cadastrado no sistema.']);
			return;
		}

		$court_id          = $this->_get_ou_criar_tribunal($tribunal);
		$location_id       = (int)($this->input->post('location_id') ?: 1);
		$court_category_id = (int)($this->input->post('court_category_id') ?: 1);
		$case_stage_id     = (int)($this->input->post('case_stage_id') ?: 1);
		$case_category_id  = json_encode([$this->input->post('case_category_id') ?: '1']);
		$act_id            = json_encode(['1']);

		$save = [
			'title'             => $titulo,
			'case_no'           => $numero,
			'client_id'         => $cliente,
			'location_id'       => $location_id,
			'court_id'          => $court_id,
			'court_category_id' => $court_category_id,
			'case_stage_id'     => $case_stage_id,
			'case_category_id'  => $case_category_id,
			'act_id'            => $act_id,
			'description'       => $descricao,
			'start_date'        => $data_inicio ?: date('Y-m-d'),
			'hearing_date'      => '0000-00-00',
			'o_lawyer'          => $polo_passivo,
			'fees'              => 0.00,
			'is_starred'        => 0,
			'is_archived'       => 0,
			'notes'             => 'Processo importado automaticamente via CNJ em ' . date('d/m/Y H:i'),
		];

		$this->db->insert('cases', $save);
		$case_id = $this->db->insert_id();

		if ($case_id) {
			echo json_encode([
				'success'  => true,
				'case_id'  => $case_id,
				'msg'      => 'Processo cadastrado com sucesso!',
				'redirect' => site_url('admin/cases/view_case/' . $case_id),
			]);
		} else {
			echo json_encode(['success' => false, 'msg' => 'Erro ao salvar no banco de dados.']);
		}
	}

	// ============================================================
	// Chamado pelo formulário add.php via POST após salvar o processo
	// para importar movimentações na tabela extended_case
	// ============================================================
	function salvar_processo_com_movimentos() {
		header('Content-Type: application/json; charset=utf-8');

		$case_id   = (int) $this->input->post('case_id');
		$movs_json = $this->input->post('movimentos_raw');

		if (!$case_id || !$movs_json) {
			echo json_encode(['success' => false, 'msg' => 'Parâmetros ausentes.']);
			return;
		}

		$movimentos = json_decode($movs_json, true);
		if (!is_array($movimentos)) {
			echo json_encode(['success' => false, 'msg' => 'JSON inválido.']);
			return;
		}

		$inseridos = 0;
		foreach ($movimentos as $mov) {
			$data_hora = $mov['dataHora'] ?? '';
			if (empty($data_hora)) continue;

			$data = date('Y-m-d', strtotime($data_hora));
			if (!$data || $data === '1970-01-01') continue;

			$nome  = trim($mov['nome'] ?? '');
			$comp  = !empty($mov['complementosTabelados'][0]['nome'])
					 ? ' — ' . $mov['complementosTabelados'][0]['nome'] : '';
			$orgao = trim($mov['orgaoJulgador']['nome'] ?? '');
			$note  = $nome . $comp . ($orgao ? ' [' . $orgao . ']' : '');

			$existe = $this->db
				->where('case_id', $case_id)
				->where('next_date', $data)
				->where('note', $note)
				->count_all_results('extended_case');

			if ($existe) continue;

			$this->db->insert('extended_case', [
				'case_id'        => $case_id,
				'next_date'      => $data,
				'last_date'      => $data,
				'note'           => $note,
				'document'       => '',
				'is_view'        => 0,
				'is_view_client' => 0,
			]);
			$inseridos++;
		}

		echo json_encode([
			'success'   => true,
			'inseridos' => $inseridos,
			'redirect'  => site_url('admin/cases/dates/' . $case_id),
		]);
	}


	private function _parse_numero_cnj($numero) {
		$pattern = '/^(\d{7})-(\d{2})\.(\d{4})\.(\d{1})\.(\d{2})\.(\d{4})$/';
		if (preg_match($pattern, $numero, $m)) {
			$tribunal_sigla = $this->_mapear_tribunal((int)$m[4], (int)$m[5]);
			return [
				'valido'   => true,
				'nnnnnnn'  => $m[1],
				'dd'       => $m[2],
				'ano'      => $m[3],
				'j'        => (int)$m[4],
				'tt'       => (int)$m[5],
				'oooo'     => $m[6],
				'tribunal' => $tribunal_sigla,
			];
		}
		return ['valido' => false, 'tribunal' => null];
	}


	private function _mapear_tribunal($j, $tt) {
		if ($j == 8) {
			$tj = [
				1=>'TJAC', 2=>'TJAL', 3=>'TJAP', 4=>'TJAM', 5=>'TJBA',
				6=>'TJCE', 7=>'TJDF', 8=>'TJES', 9=>'TJGO', 10=>'TJMA',
				11=>'TJMT', 12=>'TJMS', 13=>'TJMG', 14=>'TJPA', 15=>'TJPB',
				16=>'TJPR', 17=>'TJPE', 18=>'TJPI', 19=>'TJRJ', 20=>'TJRN',
				21=>'TJRS', 22=>'TJRO', 23=>'TJRR', 24=>'TJSC', 25=>'TJSE',
				26=>'TJSP', 27=>'TJTO',
			];
			return $tj[$tt] ?? 'TJXX';
		}
		if ($j == 5) {
			$trt = [
				1=>'TRT1',  2=>'TRT2',  3=>'TRT3',  4=>'TRT4',  5=>'TRT5',
				6=>'TRT6',  7=>'TRT7',  8=>'TRT8',  9=>'TRT9',  10=>'TRT10',
				11=>'TRT11', 12=>'TRT12', 13=>'TRT13', 14=>'TRT14', 15=>'TRT15',
				16=>'TRT16', 17=>'TRT17', 18=>'TRT18', 19=>'TRT19', 20=>'TRT20',
				21=>'TRT21', 22=>'TRT22', 23=>'TRT23', 24=>'TRT24',
			];
			return $trt[$tt] ?? 'TRTXX';
		}
		if ($j == 4) {
			$trf = [1=>'TRF1', 2=>'TRF2', 3=>'TRF3', 4=>'TRF4', 5=>'TRF5', 6=>'TRF6'];
			return $trf[$tt] ?? 'TRFXX';
		}
		return 'OUTRO';
	}


	private function _consultar_datajud($numero, $info_cnj) {
		// Lê a chave do banco (tabela settings), com fallback para constante ou chave pública atual
		$setting = $this->db->select('datajud_api_key')->get('settings')->row();
		$api_key = !empty($setting->datajud_api_key)
					? trim($setting->datajud_api_key)
					: (defined('DATAJUD_API_KEY') ? DATAJUD_API_KEY : 'cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw==');

		$tribunal = $info_cnj['tribunal'] ?? null;
		$indice   = $tribunal ? strtolower($tribunal) : null;

		if (!$indice) {
			return ['success' => false, 'fonte' => 'datajud', 'msg' => 'Tribunal não identificado no número CNJ.'];
		}

		$endpoint = 'https://api-publica.datajud.cnj.jus.br/api_publica_' . $indice . '/_search';

		// Tenta as 3 formas de query aceitas pelo DataJud, em ordem de precisão
		// DataJud armazena o número em diferentes formatos dependendo do tribunal
		// Testa: com formatação CNJ, sem formatação (só dígitos), e variações
		$numero_digits = preg_replace('/[^0-9]/', '', $numero);

		$queries = [
			// 1. Só dígitos — formato interno mais comum do DataJud
			json_encode(['query' => ['term' => ['numeroProcesso.keyword' => $numero_digits]]]),
			// 2. Com formatação CNJ (traço e pontos)
			json_encode(['query' => ['term' => ['numeroProcesso.keyword' => $numero]]]),
			// 3. match_phrase dígitos
			json_encode(['query' => ['match_phrase' => ['numeroProcesso' => $numero_digits]]]),
			// 4. match_phrase formatado
			json_encode(['query' => ['match_phrase' => ['numeroProcesso' => $numero]]]),
			// 5. match simples dígitos
			json_encode(['query' => ['match' => ['numeroProcesso' => $numero_digits]]]),
			// 6. match simples formatado
			json_encode(['query' => ['match' => ['numeroProcesso' => $numero]]]),
		];

		$headers = [
			'Content-Type: application/json',
			'Authorization: APIKey ' . $api_key,
		];

		foreach ($queries as $payload) {
			$ch = curl_init($endpoint);
			curl_setopt_array($ch, [
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_TIMEOUT        => 30,
				CURLOPT_POST           => true,
				CURLOPT_POSTFIELDS     => $payload,
				CURLOPT_HTTPHEADER     => $headers,
				CURLOPT_SSL_VERIFYPEER => false,
			]);

			$resp = curl_exec($ch);
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$err  = curl_error($ch);
			curl_close($ch);

			if ($err || $code !== 200) {
				return ['success' => false, 'fonte' => 'datajud', 'msg' => "DataJud HTTP $code" . ($err ? ": $err" : '')];
			}

			$data = json_decode($resp, true);
			$hits = $data['hits']['hits'] ?? [];

			if (!empty($hits)) {
				return $this->_montar_retorno_datajud($hits[0]['_source'] ?? [], $numero, $tribunal);
			}
		}

		// Nenhuma das queries retornou resultado — retorna debug para diagnóstico
		$data_debug  = json_decode($resp ?? '', true);
		$total       = $data_debug['hits']['total']['value'] ?? ($data_debug['hits']['total'] ?? 'N/A');
		$numero_dbg  = preg_replace('/[^0-9]/', '', $numero);

		return [
			'success' => false,
			'fonte'   => 'datajud',
			'msg'     => "Processo não encontrado no DataJud ({$tribunal}).",
			'debug'   => [
				'tribunal'       => $tribunal,
				'indice'         => $indice,
				'numero_fmt'     => $numero,
				'numero_digits'  => $numero_dbg,
				'http_code'      => $code,
				'total_hits'     => $total,
				'raw_resp'       => substr($resp ?? '', 0, 600),
			],
		];
	}


	private function _montar_retorno_datajud($proc, $numero, $tribunal) {

		// --- Classe e assuntos ---
		$classe            = $proc['classe']['nome'] ?? '';
		$assunto_principal = !empty($proc['assuntos']) ? ($proc['assuntos'][0]['nome'] ?? '') : '';
		$todos_assuntos    = implode('; ', array_filter(array_map(function($a){
			return trim($a['nome'] ?? '');
		}, $proc['assuntos'] ?? [])));

		$titulo = $classe . ($assunto_principal ? ' – ' . $assunto_principal : '');
		if (empty($titulo)) $titulo = 'Processo ' . $numero;

		// --- Data de ajuizamento ---
		// DataJud retorna em dois formatos: "20180719184852" (14 dígitos) ou ISO "2018-07-19T..."
		$data_inicio = '';
		if (!empty($proc['dataAjuizamento'])) {
			$raw = $proc['dataAjuizamento'];
			if (preg_match('/^\d{14}$/', $raw)) {
				// Formato: YYYYMMDDHHMMSS
				$data_inicio = substr($raw, 0, 4) . '-' . substr($raw, 4, 2) . '-' . substr($raw, 6, 2);
			} else {
				$data_inicio = date('Y-m-d', strtotime($raw));
			}
		}

		// --- Órgão julgador ---
		$orgao = $proc['orgaoJulgador']['nome'] ?? '';

		// --- Grau do processo ---
		$grau_map   = ['G1'=>'1º Grau','G2'=>'2º Grau','JE'=>'Juizado Especial','SUP'=>'Superior','GR'=>'Turma Recursal'];
		$grau_label = $grau_map[$proc['grau'] ?? ''] ?? ($proc['grau'] ?? '');

		// --- Sistema (PJe, e-Proc, etc.) ---
		$sistema = $proc['sistema']['nome'] ?? '';

		// --- Formato (Eletrônico, Físico) ---
		$formato = $proc['formato']['nome'] ?? '';

		// --- Partes (campo opcional — nem sempre presente no DataJud) ---
		$polo_ativo   = [];
		$polo_passivo = [];
		$advogados    = [];
		foreach ($proc['partes'] ?? [] as $parte) {
			$polo = strtoupper(trim($parte['polo'] ?? ''));
			$nome = trim($parte['nome'] ?? '');
			$polos_ativos   = ['AT','ATIVO','A','REQUERENTE','RECLAMANTE','AUTOR','EXEQUENTE','IMPETRANTE','APELANTE'];
			$polos_passivos = ['PA','PASSIVO','P','REQUERIDO','RECLAMADO','REU','RÉU','EXECUTADO','IMPETRADO','APELADO'];
			if (in_array($polo, $polos_ativos)   && $nome) $polo_ativo[]   = $nome;
			if (in_array($polo, $polos_passivos) && $nome) $polo_passivo[]  = $nome;
			foreach ($parte['advogados'] ?? [] as $adv) {
				$na = trim($adv['nome'] ?? '');
				if ($na && !in_array($na, $advogados)) $advogados[] = $na;
			}
		}

		// --- Valor da causa (campo opcional) ---
		$valor_causa = '';
		if (!empty($proc['valorCausa'])) {
			$valor_causa = 'R$ ' . number_format((float)$proc['valorCausa'], 2, ',', '.');
		}

		// --- Últimos 5 movimentos (mais recentes primeiro) ---
		$movimentos_lista = [];
		$movs_ordenados   = $proc['movimentos'] ?? [];
		usort($movs_ordenados, function($a, $b) {
			return strcmp($b['dataHora'] ?? '', $a['dataHora'] ?? '');
		});
		foreach (array_slice($movs_ordenados, 0, 5) as $mov) {
			$dt  = !empty($mov['dataHora']) ? date('d/m/Y', strtotime($mov['dataHora'])) : '';
			$nm  = trim($mov['nome'] ?? '');
			// Complemento descritivo
			$comp = '';
			if (!empty($mov['complementosTabelados'][0]['nome'])) {
				$comp = ' (' . $mov['complementosTabelados'][0]['nome'] . ')';
			}
			if ($nm) $movimentos_lista[] = $dt ? "[$dt] $nm$comp" : "$nm$comp";
		}

		// --- Audiências: busca próxima audiência designada nos movimentos ---
		$codigos_audiencia = [12747, 12748, 12749, 12750, 12751];
		$proxima_audiencia      = '';
		$proxima_audiencia_tipo = '';

		// Ordena movimentos por data decrescente para pegar o mais recente
		$movs_ord = $proc['movimentos'] ?? [];
		usort($movs_ord, function($a, $b) {
			return strcmp($b['dataHora'] ?? '', $a['dataHora'] ?? '');
		});

		foreach ($movs_ord as $mov) {
			if (!in_array($mov['codigo'] ?? 0, $codigos_audiencia)) continue;

			// Verifica complemento: situação "designada" (9) ou "redesignada" (10)
			$situacao = 0;
			foreach ($mov['complementosTabelados'] ?? [] as $comp) {
				if ($comp['descricao'] === 'situacao_da_audiencia') {
					$situacao = (int)$comp['valor'];
				}
			}

			// Pega audiências designadas ou redesignadas (não canceladas/realizadas)
			if (in_array($situacao, [9, 10])) {
				$proxima_audiencia      = !empty($mov['dataHora'])
					? date('Y-m-d', strtotime($mov['dataHora'])) : '';
				$proxima_audiencia_tipo = $mov['nome'] ?? '';
				break;
			}
		}

		// --- Monta retorno padronizado ---
		return [
			'success'               => true,
			'fonte'                 => 'datajud',
			'numero'                => $numero,
			'titulo'                => $titulo,
			'classe'                => $classe,
			'assunto'               => $assunto_principal,
			'todos_assuntos'        => $todos_assuntos,
			'data_inicio'           => $data_inicio,
			'tribunal'              => $tribunal,
			'orgao_julgador'        => $orgao,
			'grau'                  => $grau_label,
			'sistema'               => $sistema,
			'formato'               => $formato,
			'polo_ativo'            => implode('; ', $polo_ativo),
			'polo_passivo'          => implode('; ', $polo_passivo),
			'advogados'             => implode('; ', $advogados),
			'valor_causa'           => $valor_causa,
			'movimentos'            => implode("\n", $movimentos_lista),
			'descricao'             => $todos_assuntos,
			'proxima_audiencia'     => $proxima_audiencia,
			'proxima_audiencia_tipo'=> $proxima_audiencia_tipo,
			'ultima_atualizacao'    => !empty($proc['dataHoraUltimaAtualizacao'])
				? date('d/m/Y', strtotime($proc['dataHoraUltimaAtualizacao'])) : '',
			'nivel_sigilo'          => (int)($proc['nivelSigilo'] ?? 0),
			// Array bruto completo para importação na extended_case
			'movimentos_raw'        => $proc['movimentos'] ?? [],
		];
	}


	private function _consultar_worker_pje($numero) {
		if (!defined('WORKER_URL') || !defined('WORKER_SECRET')) {
			return ['success' => false, 'fonte' => 'pje', 'msg' => 'Worker PJe não configurado.'];
		}

		$url = WORKER_URL . '?action=processo&secret=' . WORKER_SECRET . '&numero=' . urlencode($numero);
		$ch  = curl_init($url);
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_TIMEOUT        => 20,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_HTTPHEADER     => ['Accept: application/json'],
		]);
		$resp = curl_exec($ch);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if ($code !== 200 || !$resp) {
			return ['success' => false, 'fonte' => 'pje', 'msg' => "Worker PJe HTTP $code"];
		}

		$data = json_decode($resp, true);
		if (empty($data['success']) || empty($data['data'])) {
			return ['success' => false, 'fonte' => 'pje', 'msg' => 'Processo não encontrado no PJe.'];
		}

		$proc = $data['data'];
		return [
			'success'        => true,
			'fonte'          => 'pje_worker',
			'numero'         => $numero,
			'titulo'         => $proc['classe'] ?? 'Processo ' . $numero,
			'classe'         => $proc['classe'] ?? '',
			'assunto'        => $proc['assunto'] ?? '',
			'data_inicio'    => isset($proc['dataAjuizamento']) ? date('Y-m-d', strtotime($proc['dataAjuizamento'])) : '',
			'tribunal'       => $proc['tribunal'] ?? '',
			'orgao_julgador' => $proc['orgaoJulgador'] ?? '',
			'polo_ativo'     => $proc['poloAtivo'] ?? '',
			'polo_passivo'   => $proc['poloPassivo'] ?? '',
			'descricao'      => $proc['assunto'] ?? '',
		];
	}


	private function _get_ou_criar_tribunal($nome_tribunal) {
		if (empty($nome_tribunal)) return 1;

		$this->db->like('name', $nome_tribunal, 'both');
		$court = $this->db->get('courts')->row();
		if ($court) return $court->id;

		$this->db->insert('courts', [
			'name'              => $nome_tribunal,
			'location_id'       => 1,
			'court_category_id' => 1,
			'description'       => 'Importado automaticamente via CNJ',
		]);
		return $this->db->insert_id();
	}



	// ============================================================
	// Importa movimentações do DataJud para a tabela extended_case
	// Chamado via AJAX após o processo ser cadastrado
	// POST: case_id, movimentos (JSON array)
	// ============================================================
	function importar_movimentos_cnj() {
		header('Content-Type: application/json; charset=utf-8');

		$case_id   = (int) $this->input->post('case_id');
		$movs_json = $this->input->post('movimentos');

		if (!$case_id || !$movs_json) {
			echo json_encode(['success' => false, 'msg' => 'Dados insuficientes.']);
			return;
		}

		$movimentos = json_decode($movs_json, true);
		if (empty($movimentos) || !is_array($movimentos)) {
			echo json_encode(['success' => false, 'msg' => 'Nenhuma movimentação recebida.']);
			return;
		}

		$inseridos = 0;
		$hoje      = date('Y-m-d');

		foreach ($movimentos as $mov) {
			$data_hora = $mov['dataHora'] ?? '';
			if (empty($data_hora)) continue;

			// Converte data ISO para Y-m-d
			$data = date('Y-m-d', strtotime($data_hora));
			if ($data === false || $data === '1970-01-01') continue;

			// Monta nota: nome + complemento
			$nome = trim($mov['nome'] ?? '');
			$comp = '';
			if (!empty($mov['complementosTabelados'][0]['nome'])) {
				$comp = ' — ' . $mov['complementosTabelados'][0]['nome'];
			}
			$orgao = trim($mov['orgaoJulgador']['nome'] ?? '');
			$note  = $nome . $comp;
			if ($orgao) $note .= ' [' . $orgao . ']';

			// Verifica duplicata (mesma data e mesma nota)
			$existe = $this->db
				->where('case_id', $case_id)
				->where('next_date', $data)
				->where('note', $note)
				->count_all_results('extended_case');

			if ($existe > 0) continue;

			$this->db->insert('extended_case', [
				'case_id'         => $case_id,
				'next_date'       => $data,
				'last_date'       => $data,
				'note'            => $note,
				'document'        => '',
				'is_view'         => 0,
				'is_view_client'  => 0,
			]);
			$inseridos++;
		}

		echo json_encode([
			'success'   => true,
			'inseridos' => $inseridos,
			'msg'       => "$inseridos movimentação(ões) importada(s) com sucesso.",
		]);
	}


	function diagnostico_cnj()
	{
		// Acesse: /index.php/admin/cases/diagnostico_cnj
		// REMOVA este método após o diagnóstico

		$numero   = '00007440920185060022'; // TRT6 testado
		$endpoint = 'https://api-publica.datajud.cnj.jus.br/api_publica_trt6/_search';

		$setting  = $this->db->select('datajud_api_key')->get('settings')->row();
		$api_key  = trim($setting->datajud_api_key ?? '');

		$payload  = json_encode(['query'=>['term'=>['numeroProcesso.keyword'=>$numero]]]);

		$ch = curl_init($endpoint);
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_CONNECTTIMEOUT => 10,
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => $payload,
			CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: APIKey '.$api_key],
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; LawSystem/1.0)',
			CURLOPT_FOLLOWLOCATION => true,
		]);
		$resp = curl_exec($ch);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$err  = curl_error($ch);
		curl_close($ch);

		$data = json_decode($resp, true);
		$hits = $data['hits']['total']['value'] ?? 0;

		header('Content-Type: text/html; charset=utf-8');
		echo "<style>body{font-family:monospace;padding:20px} b{color:#00539B}</style>";
		echo "<h3>Diagnóstico CNJ</h3>";
		echo "<b>API Key (15 chars):</b> " . substr($api_key,0,15) . "...<br>";
		echo "<b>HTTP:</b> $code<br>";
		if ($err) echo "<b>CURL erro:</b> $err<br>";
		echo "<b>Hits:</b> $hits<br><br>";

		if (!empty($data['hits']['hits'])) {
			$proc = $data['hits']['hits'][0]['_source'];
			echo "<b>dataAjuizamento:</b> " . ($proc['dataAjuizamento']??'N/A') . "<br>";
			echo "<b>grau:</b> " . ($proc['grau']??'N/A') . "<br>";
			echo "<b>classe:</b> " . ($proc['classe']['nome']??'N/A') . "<br>";
			echo "<b>orgaoJulgador:</b> " . ($proc['orgaoJulgador']['nome']??'N/A') . "<br>";
			echo "<b>partes:</b> " . (isset($proc['partes']) ? count($proc['partes']).' partes' : 'CAMPO AUSENTE') . "<br>";
			echo "<b>valorCausa:</b> " . ($proc['valorCausa']??'CAMPO AUSENTE') . "<br>";
			echo "<b>movimentos:</b> " . count($proc['movimentos']??[]) . "<br><br>";

			// Simula _montar_retorno_datajud
			$raw = $proc['dataAjuizamento'] ?? '';
			$data_inicio = '';
			if (preg_match('/^\d{14}$/', $raw)) {
				$data_inicio = substr($raw,0,4).'-'.substr($raw,4,2).'-'.substr($raw,6,2);
			} elseif ($raw) {
				$data_inicio = date('Y-m-d', strtotime($raw));
			}
			echo "<hr><b>Simulação do retorno PHP:</b><br>";
			echo "data_inicio: <b>$data_inicio</b><br>";
			$grau_map = ['G1'=>'1º Grau','G2'=>'2º Grau','JE'=>'Juizado Especial'];
			echo "grau_label: <b>" . ($grau_map[$proc['grau']??'']??$proc['grau']??'') . "</b><br>";
			echo "titulo: <b>" . ($proc['classe']['nome']??'') . " – " . ($proc['assuntos'][0]['nome']??'') . "</b><br>";

			$movs = $proc['movimentos'] ?? [];
			usort($movs, fn($a,$b) => strcmp($b['dataHora']??'', $a['dataHora']??''));
			echo "ultimo_mov: <b>[" . ($movs ? date('d/m/Y', strtotime($movs[0]['dataHora'])) : 'N/A') . "] " . ($movs[0]['nome']??'') . "</b><br>";

			$info_cnj = $this->_parse_numero_cnj('0000744-09.2018.5.06.0022');
			echo "<br><b>_parse_numero_cnj:</b> " . json_encode($info_cnj) . "<br>";
		} else {
			echo "<b style='color:red'>Processo não encontrado com term.keyword</b><br>";
			echo "<pre>" . htmlspecialchars(substr($resp??'',0,300)) . "</pre>";
		}
	}


	// ============================================================
	// SINCRONIZAR MOVIMENTAÇÕES — chamado via AJAX na view do processo
	// URL: admin/cases/sincronizar_movimentacoes/ID
	// ============================================================
	function sincronizar_movimentacoes($case_id = 0)
	{
		header('Content-Type: application/json; charset=utf-8');
		$case_id = (int)$case_id;

		if (!$case_id) {
			echo json_encode(['success' => false, 'msg' => 'ID inválido.']);
			return;
		}

		$case = $this->db->where('id', $case_id)->get('cases')->row();
		if (!$case) {
			echo json_encode(['success' => false, 'msg' => 'Processo não encontrado.']);
			return;
		}

		$numero_digits = preg_replace('/[^0-9]/', '', $case->case_no);
		$tribunal = $this->_parse_numero_cnj($case->case_no)['tribunal'] ?? null;
		$indice   = $tribunal ? strtolower($tribunal) : null;

		if (!$indice) {
			echo json_encode(['success' => false, 'msg' => 'Número CNJ inválido ou tribunal não identificado.']);
			return;
		}

		$setting = $this->db->select('datajud_api_key')->get('settings')->row();
		$api_key = trim($setting->datajud_api_key ?? '');

		$endpoint = 'https://api-publica.datajud.cnj.jus.br/api_publica_' . $indice . '/_search';
		$payload  = json_encode(['query' => ['term' => ['numeroProcesso.keyword' => $numero_digits]]]);

		$ch = curl_init($endpoint);
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_CONNECTTIMEOUT => 10,
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => $payload,
			CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: APIKey ' . $api_key],
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; LawSystem/1.0)',
		]);
		$resp = curl_exec($ch);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if ($code !== 200 || !$resp) {
			echo json_encode(['success' => false, 'msg' => "DataJud HTTP {$code}"]);
			return;
		}

		$data = json_decode($resp, true);
		$hits = $data['hits']['hits'] ?? [];

		if (empty($hits)) {
			echo json_encode(['success' => false, 'msg' => 'Processo não encontrado no DataJud.']);
			return;
		}

		$proc       = $hits[0]['_source'] ?? [];
		$movimentos = $proc['movimentos'] ?? [];
		$inseridos  = 0;

		foreach ($movimentos as $mov) {
			$data_hora = $mov['dataHora'] ?? '';
			if (empty($data_hora)) continue;

			$data_mov = date('Y-m-d', strtotime($data_hora));
			$nome     = trim($mov['nome'] ?? '');
			$comp     = !empty($mov['complementosTabelados'][0]['nome'])
						? ' — ' . $mov['complementosTabelados'][0]['nome'] : '';
			$orgao    = trim($mov['orgaoJulgador']['nome'] ?? '');
			$note     = $nome . $comp . ($orgao ? ' [' . $orgao . ']' : '');

			$existe = $this->db
				->where('case_id', $case_id)
				->where('next_date', $data_mov)
				->where('note', $note)
				->count_all_results('extended_case');

			if ($existe) continue;

			$this->db->insert('extended_case', [
				'case_id'        => $case_id,
				'next_date'      => $data_mov,
				'last_date'      => $data_mov,
				'note'           => $note,
				'document'       => '',
				'is_view'        => 0,
				'is_view_client' => 0,
			]);
			$inseridos++;
		}

		// Atualiza data de sincronização
		$this->db->where('id', $case_id)->update('cases', [
			'datajud_ultima_sync' => date('Y-m-d H:i:s'),
			'datajud_total_movs'  => $this->db->query(
				"SELECT COUNT(*) as t FROM extended_case WHERE case_id = {$case_id}"
			)->row()->t ?? 0,
		]);

		// Registra no log
		$this->db->insert('oab_sync_log', [
			'tipo'      => 'movimentacao',
			'case_id'   => $case_id,
			'case_no'   => $case->case_no,
			'status'    => 'ok',
			'movs_novas'=> $inseridos,
			'origem'    => 'manual',
		]);

		echo json_encode([
			'success'   => true,
			'inseridos' => $inseridos,
			'total_movs'=> count($movimentos),
			'msg'       => $inseridos > 0
				? "{$inseridos} nova(s) movimentação(ões) importada(s)!"
				: "Processo já está atualizado. Nenhuma novidade.",
		]);
	}


	// ============================================================
	// PROCESSOS PENDENTES OAB — lista para importação
	// URL: admin/cases/processos_oab_pendentes
	// ============================================================
	function processos_oab_pendentes()
	{
		$data['pendentes'] = $this->db
			->where('status', 'pendente')
			->order_by('encontrado_em', 'DESC')
			->get('oab_processos_pendentes')
			->result();

		$data['clients'] = $this->cases_model->get_all_clients();
		$this->load->view('template/header');
		$this->load->view('case/oab_pendentes', $data);
		$this->load->view('template/footer');
	}


	// ============================================================
	// IGNORAR processo pendente OAB
	// URL: admin/cases/ignorar_pendente/ID
	// ============================================================
	function ignorar_pendente($id = 0)
	{
		$this->db->where('id', (int)$id)->update('oab_processos_pendentes', ['status' => 'ignorado']);
		redirect('admin/cases/processos_oab_pendentes');
	}


	// ============================================================
	// STATUS SYNC — retorna dados de sincronização para AJAX
	// URL: admin/cases/status_sync/ID
	// ============================================================
	function status_sync($case_id = 0)
	{
		header('Content-Type: application/json; charset=utf-8');
		$case = $this->db->select('datajud_ultima_sync, datajud_total_movs, datajud_monitorar, case_no')
			->where('id', (int)$case_id)->get('cases')->row();

		if (!$case) { echo json_encode(['success' => false]); return; }

		$ultima = $case->datajud_ultima_sync;
		$label  = $ultima ? date('d/m/Y H:i', strtotime($ultima)) : 'Nunca sincronizado';
		$horas  = $ultima ? round((time() - strtotime($ultima)) / 3600, 1) : null;

		echo json_encode([
			'success'         => true,
			'ultima_sync'     => $label,
			'horas_atras'     => $horas,
			'total_movs'      => (int)$case->datajud_total_movs,
			'monitorar'       => (int)$case->datajud_monitorar,
			'tem_numero_cnj'  => !empty($case->case_no),
		]);
	}


	// ============================================================
	// IMPORTAR processos selecionados da fila OAB
	// POST: ids (csv), client_id
	// ============================================================
	function importar_processos_oab()
	{
		header('Content-Type: application/json; charset=utf-8');
		$ids_raw   = $this->input->post('ids');
		$client_id = (int)$this->input->post('client_id');

		if (!$ids_raw || !$client_id) {
			echo json_encode(['success' => false, 'msg' => 'Parâmetros inválidos.']);
			return;
		}

		$ids       = array_filter(array_map('intval', explode(',', $ids_raw)));
		$importados = 0;
		$erros     = [];

		foreach ($ids as $id) {
			$pendente = $this->db->where('id', $id)->where('status', 'pendente')
				->get('oab_processos_pendentes')->row();
			if (!$pendente) continue;

			// Verifica duplicata
			$existe = $this->db->where('case_no', $pendente->numero_cnj)
				->count_all_results('cases');
			if ($existe > 0) {
				$this->db->where('id', $id)->update('oab_processos_pendentes', ['status' => 'importado']);
				continue;
			}

			// Busca dados completos do JSON salvo
			$dados = json_decode($pendente->dados_json, true) ?? [];

			$court_id = $this->_get_ou_criar_tribunal(
				($pendente->tribunal ?? '') . ' — ' . ($pendente->orgao ?? '')
			);

			$save = [
				'title'             => ($pendente->classe ?: 'Processo') . ($pendente->assunto ? ' – ' . $pendente->assunto : ''),
				'case_no'           => $pendente->numero_cnj,
				'client_id'         => $client_id,
				'location_id'       => 1,
				'court_id'          => $court_id,
				'court_category_id' => 1,
				'case_stage_id'     => 1,
				'case_category_id'  => json_encode(['1']),
				'act_id'            => json_encode(['1']),
				'description'       => implode("\n", array_filter([
					$pendente->assunto ? 'Assunto: ' . $pendente->assunto : null,
					$pendente->grau    ? 'Grau: '    . $pendente->grau    : null,
					$pendente->orgao   ? 'Vara: '    . $pendente->orgao   : null,
					$pendente->polo_ativo   ? 'Polo Ativo: '   . $pendente->polo_ativo   : null,
					$pendente->polo_passivo ? 'Polo Passivo: ' . $pendente->polo_passivo : null,
					$pendente->valor_causa > 0 ? 'Valor: R$ ' . number_format($pendente->valor_causa, 2, ',', '.') : null,
				])),
				'start_date'        => $pendente->data_inicio ?: date('Y-m-d'),
				'hearing_date'      => '0000-00-00',
				'o_lawyer'          => $pendente->polo_passivo ?? '',
				'fees'              => 0.00,
				'is_starred'        => 0,
				'is_archived'       => 0,
				'notes'             => 'Importado via busca OAB em ' . date('d/m/Y H:i'),
				'cnj_importado_em'  => date('Y-m-d H:i:s'),
				'cnj_tribunal_sigla'=> $pendente->tribunal ?? '',
			];

			$this->db->insert('cases', $save);
			$case_id = $this->db->insert_id();

			if ($case_id) {
				// Importa movimentações do JSON salvo
				$movimentos = $dados['movimentos'] ?? [];
				foreach ($movimentos as $mov) {
					$data_hora = $mov['dataHora'] ?? '';
					if (!$data_hora) continue;
					$data_mov = date('Y-m-d', strtotime($data_hora));
					$nome     = trim($mov['nome'] ?? '');
					$comp     = !empty($mov['complementosTabelados'][0]['nome']) ? ' — ' . $mov['complementosTabelados'][0]['nome'] : '';
					$orgao    = trim($mov['orgaoJulgador']['nome'] ?? '');
					$note     = $nome . $comp . ($orgao ? ' [' . $orgao . ']' : '');
					$this->db->insert('extended_case', [
						'case_id' => $case_id, 'next_date' => $data_mov, 'last_date' => $data_mov,
						'note' => $note, 'document' => '', 'is_view' => 0, 'is_view_client' => 0,
					]);
				}

				$this->db->where('id', $id)->update('oab_processos_pendentes', [
					'status'  => 'importado',
					'case_id' => $case_id,
				]);
				$importados++;
			}
		}

		echo json_encode([
			'success' => true,
			'msg'     => "{$importados} processo(s) importado(s) com sucesso!",
		]);
	}


	// ============================================================
	// BUSCA MANUAL OAB — dispara a busca imediatamente
	// URL: admin/cases/buscar_oab_agora
	// ============================================================
	function buscar_oab_agora()
	{
		header('Content-Type: application/json; charset=utf-8');

		$setting  = $this->db->get('settings')->row();
		$api_key  = trim($setting->datajud_api_key ?? '');
		$oab_num  = trim($setting->oab_numero ?? '');
		$oab_uf   = strtoupper(trim($setting->oab_uf ?? 'PE'));

		if (empty($oab_num)) {
			echo json_encode(['success' => false, 'msg' => 'Número OAB não configurado em Configurações Gerais.']);
			return;
		}

		// Mapeia UF para tribunais
		$tribunais_por_uf = [
			'PE' => ['tjpe', 'trt6', 'trf5'],
			'SP' => ['tjsp', 'trt2', 'trt15', 'trf3'],
			'RJ' => ['tjrj', 'trt1', 'trf2'],
			'MG' => ['tjmg', 'trt3', 'trf1'],
			'RS' => ['tjrs', 'trt4', 'trf4'],
			'PR' => ['tjpr', 'trt9', 'trf4'],
			'SC' => ['tjsc', 'trt12', 'trf4'],
			'BA' => ['tjba', 'trt5', 'trf1'],
			'CE' => ['tjce', 'trt7', 'trf5'],
			'GO' => ['tjgo', 'trt18', 'trf1'],
		];
		$tribunais = $tribunais_por_uf[$oab_uf] ?? ['tjpe', 'trt6', 'trf5'];

		$novos    = 0;
		$detalhes = [];

		foreach ($tribunais as $indice) {
			$endpoint = 'https://api-publica.datajud.cnj.jus.br/api_publica_' . $indice . '/_search';
			$payload  = json_encode([
				'size'  => 100,
				'query' => [
					'nested' => [
						'path'  => 'partes',
						'query' => [
							'nested' => [
								'path'  => 'partes.advogados',
								'query' => [
									'match' => ['partes.advogados.numeroOAB' => $oab_num]
								]
							]
						]
					]
				]
			]);

			$ch = curl_init($endpoint);
			curl_setopt_array($ch, [
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_TIMEOUT        => 30,
				CURLOPT_CONNECTTIMEOUT => 10,
				CURLOPT_POST           => true,
				CURLOPT_POSTFIELDS     => $payload,
				CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: APIKey ' . $api_key],
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; LawSystem/1.0)',
			]);
			$resp = curl_exec($ch);
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);

			if ($code !== 200 || !$resp) {
				$detalhes[] = strtoupper($indice) . ': HTTP ' . $code;
				continue;
			}

			$data = json_decode($resp, true);
			$hits = $data['hits']['hits'] ?? [];
			$encontrados = count($hits);
			$detalhes[] = strtoupper($indice) . ': ' . $encontrados . ' processo(s)';

			foreach ($hits as $hit) {
				$proc   = $hit['_source'] ?? [];
				$numero = $proc['numeroProcesso'] ?? '';
				if (empty($numero)) continue;

				// Formata número CNJ
				$numero_fmt = $numero;
				if (preg_match('/^(\d{7})(\d{2})(\d{4})(\d{1})(\d{2})(\d{4})$/', $numero, $m)) {
					$numero_fmt = "{$m[1]}-{$m[2]}.{$m[3]}.{$m[4]}.{$m[5]}.{$m[6]}";
				}

				// Verifica se já cadastrado
				$existe_case = $this->db->where('case_no', $numero_fmt)
					->or_where('case_no', $numero)
					->count_all_results('cases');
				if ($existe_case) continue;

				// Verifica se já está na fila
				$existe_fila = $this->db->where('numero_cnj', $numero_fmt)
					->count_all_results('oab_processos_pendentes');
				if ($existe_fila) continue;

				// Extrai dados
				$classe      = $proc['classe']['nome'] ?? '';
				$assunto     = !empty($proc['assuntos']) ? ($proc['assuntos'][0]['nome'] ?? '') : '';
				$orgao       = $proc['orgaoJulgador']['nome'] ?? '';
				$grau        = $proc['grau'] ?? '';
				$valor       = (float)($proc['valorCausa'] ?? 0);
				$data_raw    = $proc['dataAjuizamento'] ?? '';
				$data_inicio = '';
				if ($data_raw && preg_match('/^\d{14}$/', $data_raw)) {
					$data_inicio = substr($data_raw,0,4).'-'.substr($data_raw,4,2).'-'.substr($data_raw,6,2);
				} elseif ($data_raw) {
					$data_inicio = date('Y-m-d', strtotime($data_raw));
				}

				$polos_a = []; $polos_p = [];
				foreach ($proc['partes'] ?? [] as $parte) {
					$polo = strtoupper(trim($parte['polo'] ?? ''));
					$nome = trim($parte['nome'] ?? '');
					if (in_array($polo, ['AT','ATIVO','REQUERENTE','RECLAMANTE','AUTOR','EXEQUENTE'])) $polos_a[] = $nome;
					if (in_array($polo, ['PA','PASSIVO','REQUERIDO','RECLAMADO','REU','RÉU','EXECUTADO'])) $polos_p[] = $nome;
				}

				$this->db->insert('oab_processos_pendentes', [
					'numero_cnj'   => $numero_fmt,
					'tribunal'     => strtoupper($indice),
					'classe'       => $classe,
					'assunto'      => $assunto,
					'data_inicio'  => $data_inicio ?: null,
					'orgao'        => $orgao,
					'polo_ativo'   => implode('; ', $polos_a),
					'polo_passivo' => implode('; ', $polos_p),
					'valor_causa'  => $valor,
					'grau'         => $grau,
					'dados_json'   => json_encode($proc),
				]);
				$novos++;
			}

			usleep(400000);
		}

		// Registra no log
		$this->db->insert('oab_sync_log', [
			'tipo'           => 'oab_busca',
			'oab_numero'     => $oab_num,
			'status'         => 'ok',
			'processos_novos'=> $novos,
			'mensagem'       => implode(' | ', $detalhes),
			'origem'         => 'manual',
		]);

		echo json_encode([
			'success'  => true,
			'novos'    => $novos,
			'detalhes' => $detalhes,
			'msg'      => $novos > 0
				? "{$novos} novo(s) processo(s) encontrado(s) e adicionado(s) à fila de importação."
				: "Nenhum processo novo encontrado. Todos já estão cadastrados ou na fila.",
		]);
	}


	// ============================================================
	// LOG DE SINCRONIZAÇÕES — para exibir no painel
	// URL: admin/cases/log_sincronizacoes
	// ============================================================
	function log_sincronizacoes()
	{
		header('Content-Type: application/json; charset=utf-8');
		$logs = $this->db
			->order_by('created_at', 'DESC')
			->limit(50)
			->get('oab_sync_log')
			->result();

		echo json_encode(['success' => true, 'logs' => $logs]);
	}


	// Diagnóstico OAB — acesse /index.php/admin/cases/diagnostico_oab
	function diagnostico_oab()
	{
		header('Content-Type: text/html; charset=utf-8');
		$setting = $this->db->get('settings')->row();
		$api_key = trim($setting->datajud_api_key ?? '');
		$oab_num = trim($setting->oab_numero ?? '');
		$oab_uf  = strtoupper(trim($setting->oab_uf ?? 'PE'));

		echo "<style>body{font-family:monospace;padding:20px} pre{background:#111;color:#0f0;padding:12px;border-radius:6px;overflow:auto;font-size:11px}</style>";
		echo "<h3>Diagnóstico OAB</h3>";
		echo "OAB: <b>$oab_num / $oab_uf</b><br>";
		echo "API Key: <b>" . substr($api_key,0,20) . "...</b><br><br>";

		if (empty($oab_num)) { echo "<b style='color:red'>OAB não configurada!</b>"; return; }

		// Testa com TJPE
		$endpoint = "https://api-publica.datajud.cnj.jus.br/api_publica_tjpe/_search";
		$payload  = json_encode([
			'size'  => 5,
			'query' => [
				'nested' => [
					'path'  => 'partes',
					'query' => [
						'nested' => [
							'path'  => 'partes.advogados',
							'query' => ['match' => ['partes.advogados.numeroOAB' => $oab_num]]
						]
					]
				]
			]
		]);

		$ch = curl_init($endpoint);
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_CONNECTTIMEOUT => 10,
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => $payload,
			CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Authorization: APIKey ' . $api_key],
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; LawSystem/1.0)',
		]);
		$resp = curl_exec($ch);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$err  = curl_error($ch);
		curl_close($ch);

		echo "HTTP: <b>$code</b><br>";
		if ($err) echo "CURL erro: <b style='color:red'>$err</b><br>";

		$data = json_decode($resp, true);
		$hits = count($data['hits']['hits'] ?? []);
		$total = $data['hits']['total']['value'] ?? 0;
		echo "Total processos TJPE: <b>$total</b> | Retornados: <b>$hits</b><br><br>";

		if ($hits > 0) {
			$proc = $data['hits']['hits'][0]['_source'] ?? [];
			echo "<b>Primeiro processo:</b><br>";
			echo "Número: " . ($proc['numeroProcesso'] ?? '?') . "<br>";
			echo "Classe: " . ($proc['classe']['nome'] ?? '?') . "<br>";
			echo "Partes: " . count($proc['partes'] ?? []) . "<br>";
			$adv = [];
			foreach ($proc['partes'] ?? [] as $p) {
				foreach ($p['advogados'] ?? [] as $a) $adv[] = ($a['nome'] ?? '') . ' OAB:' . ($a['numeroOAB'] ?? '');
			}
			echo "Advogados: " . implode(', ', $adv) . "<br>";
		}

		echo "<br><b>Payload enviado:</b><pre>" . htmlspecialchars($payload) . "</pre>";
		echo "<b>Response (primeiros 500 chars):</b><pre>" . htmlspecialchars(substr($resp??'',0,500)) . "</pre>";
	}

}