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

class Apply_Job extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();   
        $this->load->library('session'); 
        $allowed_methods = ['submit_application'];
        if (!in_array($this->router->fetch_method(), $allowed_methods) && $this->session->userdata('validated') != true)
        {
            redirect('login');
        }      
        $this->load->helper('url');
        $this->load->model('Apply_Job_Model');
        $this->load->model('Apply_Job_Model','category'); 
    }

    public function index() 
    {
        $this->load->helper('url');        
        $data["extra_js"] = array("apply-job");
        $data['controller'] = base_url('apply-job');
        $data['page_title'] = "Job Applications | CMS";
        $data['page_heading'] = "Job Applications";
        $data['main_content'] = 'apply_job/list_view';
        $this->load->view('main_content', $data);
    }
 
    public function submit_application()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json");

        date_default_timezone_set('Asia/Calcutta'); 
        
        $this->load->library('upload');
        $resume = "";      
        
        // Check if files directory exists, if not create it
        $upload_path = FCPATH . '../assets/uploads/resume';
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0777, true);
        }
         
        if(!empty($_FILES['resume']['name']))
        {
            $config = array();
            $config['upload_path'] = $upload_path; 
            $config['allowed_types'] = 'pdf|doc|docx';
            $config['max_size'] = '5120'; // 5MB
            $config['encrypt_name'] = TRUE;
            
            $this->upload->initialize($config); 
            if($this->upload->do_upload('resume'))
            { 
                $resume_data = $this->upload->data(); 
                $resume = $resume_data['file_name'];
            }
            else
            { 
                $error = $this->upload->display_errors();
                echo json_encode([
                    "status" => "error", 
                    "message" => "File upload error: " . strip_tags($error)
                ]);
                exit;
            }
        }

        // Validate required fields
        if(empty($this->input->post('fullName')) || empty($this->input->post('phone')) || empty($this->input->post('email'))) {
            echo json_encode([
                "status" => "error", 
                "message" => "Please fill all required fields"
            ]);
            exit;
        }

        $data = array(
            'apply_for' => $this->input->post('position'),
            'name' => $this->input->post('fullName'),
            'mobile_no' => $this->input->post('phone'),
            'email' => $this->input->post('email'),
            'current_location' => $this->input->post('currentLocation'),
            'total_experience' => $this->input->post('totalExperience'),
            'current_ctc' => $this->input->post('currentCTC'),
            'message' => $this->input->post('optionalInfo'),
            'resume' => $resume,
            'date_time' => date("Y-m-d H:i:s"),
            'status' => '1',
            'publish' => '1'
        );

        $insert_id = $this->db->insert(TBL_APPLY_JOB, $data);

        if($insert_id) {
            echo json_encode([
                "status" => "ok", 
                "message" => "Application submitted successfully"
            ]);
        } else {
            echo json_encode([
                "status" => "error", 
                "message" => "Failed to submit application"
            ]);
        }
        exit;
    }

    public function ajax_list()
    {
        $this->db->query("DELETE FROM ".TBL_APPLY_JOB." WHERE id NOT IN(
           SELECT t.id FROM (SELECT MIN(id) AS id FROM ".TBL_APPLY_JOB." GROUP BY name) AS t)"); 
        
        $list = $this->category->get_datatables();
        $data = array();
        $no = $_POST['start'] + 1;
        foreach ($list as $category) {
            $row = array();
            $row[] = $no++; 
            $row[] = $category->apply_for;
            $row[] = ucwords(strtolower($category->name));
            $row[] = $category->mobile_no;
            $row[] = $category->email;
            $row[] = $category->current_location;
            $row[] = $category->total_experience;
            $row[] = $category->current_ctc;
            $row[] = date("d-m-Y g:i A", strtotime($category->date_time)); 
            
            if($category->status == '1')
                $row[] = '<span class="badge badge-warning">Pending</span>';   
            else
                $row[] = '<span class="badge badge-success">Complete</span>';
            
            if(!empty($category->resume))
            { 
                $resume_path = base_url("../assets/uploads/resume/".$category->resume);
                $row[] = '<a href="'.$resume_path.'" target="_blank" class="btn btn-sm btn-info" download><i class="fa fa-download"></i></a>'; 
            }
            else
            {
                $row[] = '---';
            }
            
            $row[] = '<a type="button" href="javascript:void(0);" onclick="view_data('."'".$category->id."'".')" class="btn btn-sm btn-primary" title="View"><i class="fa fa-eye"></i></a>
                <a type="button" href="javascript:void(0);" onclick="mark_complete('."'".$category->id."'".')" class="btn btn-sm btn-success" title="Mark Complete"><i class="fa fa-check"></i></a>
                <a class="delete_btn btn btn-sm btn-danger" href="javascript:" title="Delete" data-id="'.$category->id.'"><i class="fa fa-trash"></i></a>';

            $data[] = $row;
        }
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->category->count_all(),
            "recordsFiltered" => $this->category->count_filtered(),
            "data" => $data,
        ); 
        echo json_encode($output);
    }

    public function view($id)
    {
        $row = $this->category->get_by_id($id);
        echo json_encode($row);
    }

    public function category_active($id)
    { 
        $sql = "UPDATE ". TBL_APPLY_JOB ." SET status='0' WHERE id ='".$id."'";       
        $this->db->query($sql);
        echo json_encode(["success"]);
    }

    public function category_deactive($id)
    { 
        $sql = "UPDATE ". TBL_APPLY_JOB ." SET status='1' WHERE id ='".$id."'";       
        $this->db->query($sql);
        echo json_encode(["success"]);
    }

    public function ajax_delete($id)
    {
        $get_id = $id;
        $sql_query = $this->db->query("SELECT id, resume FROM ".TBL_APPLY_JOB." WHERE id='$get_id'")->row(); 
        if (isset($sql_query))
        {   
            $resume = $sql_query->resume;
            if(!empty($resume))
            {
                $resume_path = FCPATH . '../assets/uploads/resume/' . $resume; 
                if(file_exists($resume_path)) {
                    unlink($resume_path);
                }
            }
        }
        $this->category->delete_by_id($get_id);
        $response = array("status" => "ok", "heading" => "Deleted", "message" => "Record Deleted Successfully.");
        echo json_encode($response);  
        die;
    }
}