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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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');
        $this->load->model('Email_Format_Model', 'email_format_model');
        $this->load->model('Admin_Email_Format_Model', 'admin_email_format_model');
        $this->load->model('Email_Notification_Settings_Model', 'ens_model');

        require_once APPPATH.'third_party/PHPMailer/Exception.php';
        require_once APPPATH.'third_party/PHPMailer/PHPMailer.php';
        require_once APPPATH.'third_party/PHPMailer/SMTP.php';
    }

    private function sendMail($from, $to, $subject, $body)
    {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'localhost';
            $mail->SMTPAuth   = false;
            $mail->Port       = 25;
            $mail->CharSet    = 'UTF-8';

            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            $mail->setFrom($from, 'Synergy Hospital');
            $recipients = explode(',', $to);
            foreach ($recipients as $recipient) {
                $mail->addAddress(trim($recipient));
            }
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            $mail->send();
            return true;
        } catch (Exception $e) {
            log_message('error', 'PHPMailer Error: ' . $mail->ErrorInfo);
            return false;
        }
    }

    private function replacePlaceholders($template, $data)
    {
        foreach ($data as $key => $value) {
            $template = str_replace('{' . $key . '}', htmlspecialchars($value ?? ''), $template);
        }
        return $template;
    }

    private function buildEmailBody($top_desc, $bottom_desc, $table_rows_html)
    {
        return '
        <div style="font-family:Arial,sans-serif;max-width:600px;margin:auto;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden;">
          <div style="background:#003773;padding:20px;text-align:center;">
            <h2 style="color:#fff;margin:0;">Synergy Hospital</h2>
          </div>
          <div style="padding:30px;">
            <div style="margin-bottom:15px;">' . $top_desc . '</div>
            <table style="width:100%;border-collapse:collapse;margin:15px 0;">' . $table_rows_html . '</table>
            <div style="margin-top:15px;color:#555;">' . $bottom_desc . '</div>
          </div>
          <div style="background:#f5f5f5;padding:15px;text-align:center;font-size:12px;color:#999;">
            Synergy Hospital &mdash; HR Department
          </div>
        </div>';
    }

    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'))) {
            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'),
            'qualification' => $this->input->post('qualification'),
            '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) {

            $placeholders = [
                'name'             => $data['name'],
                'position'         => $data['apply_for'],
                'mobile'           => $data['mobile_no'],
                'email'            => $data['email'],
                'location'         => $data['current_location'],
                'experience'       => $data['total_experience'],
                'current_ctc'      => $data['current_ctc'],
                'message'          => $data['message'] ?? '-',
                'hospital_name'    => 'Synergy Hospital',
                'hospital_email'   => 'hrhead@synergyhospital.co.in',
            ];

            $table_rows = '
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Position</strong></td><td style="padding:10px;border:1px solid #dde;">{position}</td></tr>
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Name</strong></td><td style="padding:10px;border:1px solid #dde;">{name}</td></tr>
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Mobile</strong></td><td style="padding:10px;border:1px solid #dde;">{mobile}</td></tr>
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Email</strong></td><td style="padding:10px;border:1px solid #dde;">{email}</td></tr>
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Location</strong></td><td style="padding:10px;border:1px solid #dde;">{location}</td></tr>
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Experience</strong></td><td style="padding:10px;border:1px solid #dde;">{experience}</td></tr>
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Current CTC</strong></td><td style="padding:10px;border:1px solid #dde;">{current_ctc}</td></tr>
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Message</strong></td><td style="padding:10px;border:1px solid #dde;">{message}</td></tr>';
            $table_rows = $this->replacePlaceholders($table_rows, $placeholders);

            if (!empty($data['resume'])) {
                $resume_url = base_url('../assets/uploads/resume/' . $data['resume']);
                $table_rows .= '
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Resume</strong></td><td style="padding:10px;border:1px solid #dde;"><a href="' . $resume_url . '" target="_blank" style="color:#003773;text-decoration:underline;">Download Resume</a></td></tr>';
            }

            // Fetch Email settings from database
            $from_email = 'system@synergyhospital.co.in';
            $to_email = 'hrhead@synergyhospital.co.in';
            $settings = $this->ens_model->get_by_form_key('career');
            if ($settings) {
                if (!empty($settings->from_email)) $from_email = $settings->from_email;
                if (!empty($settings->to_emails)) $to_email = $settings->to_emails;
            }

            // ========== Applicant Email (Template ID = 4 for Job Apply) ==========
            $patient_tpl = $this->email_format_model->get_by_id(4);
            if ($patient_tpl) {
                $p_subject = $this->replacePlaceholders($patient_tpl->subject, $placeholders);
                $p_top     = $this->replacePlaceholders($patient_tpl->top_description, $placeholders);
                $p_bottom  = $this->replacePlaceholders($patient_tpl->bottom_description, $placeholders);
                $p_body    = $this->buildEmailBody($p_top, $p_bottom, $table_rows);
            } else {
                $p_subject = "Application Received - Synergy Hospital";
                $p_body    = $this->buildEmailBody(
                    'Dear <strong>' . htmlspecialchars($data['name']) . '</strong>, we have received your job application.',
                    'Our HR team will contact you soon. Email: <strong>hrhead@synergyhospital.co.in</strong>.',
                    $table_rows
                );
            }
            if (!empty($data['email'])) {
                $this->sendMail($from_email, $data['email'], $p_subject, $p_body);
            }

            // ========== Admin Email (Template ID = 4 for Job Apply) ==========
            $admin_tpl = $this->admin_email_format_model->get_by_id(4);
            if ($admin_tpl) {
                $a_subject = $this->replacePlaceholders($admin_tpl->subject, $placeholders);
                $a_top     = $this->replacePlaceholders($admin_tpl->top_description, $placeholders);
                $a_bottom  = $this->replacePlaceholders($admin_tpl->bottom_description, $placeholders);
                $a_body    = $this->buildEmailBody($a_top, $a_bottom, $table_rows);
            } else {
                $a_subject = "New Job Application - " . $data['apply_for'] . " (" . $data['name'] . ")";
                $a_body    = $this->buildEmailBody(
                    'New application for <strong>' . htmlspecialchars($data['apply_for']) . '</strong> from <strong>' . htmlspecialchars($data['name']) . '</strong>.',
                    'Log in to admin panel for full details.',
                    $table_rows
                );
            }
            $this->sendMail($from_email, $to_email, $a_subject, $a_body);

            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;
    }
}