<?php

namespace App\Controllers;

use App\Models\VacancyModel;
use App\Models\SectorModel;
use App\Models\SkillsModel;
use App\Models\InterestModel;
use App\Models\CompanyModel;
use App\Models\CompanySectorModel;
use Exception;

class DashboardController extends BaseController
{
    public function getToken()
    {
        $session = session();
        return $session->get('token');
    }

    public function index()
    {
        $judul = [
            'title' => 'Dashboard'
        ];
        if (!session()->get('loggedIn')) {
            return redirect()->to('company/login');
        }
        $session = session();
        $coba = $session->get('token');

        // Tampilkan halaman login jika belum login
        return view('company/dashboard', $judul);
    }

    public function registerCompany()
    {
        $sectorModel = new SectorModel();
        $data['sectors'] = $sectorModel->getSectors();
        return view('company/register', $data);
    }

    public function submitCompanyRegister()
    {
        $session = session();
        $model = new CompanyModel();
        $companyData = $this->request->getPost();
        $newCompanyName = $companyData['name'];
        $response = $model->registerCompany($companyData);

        if ($response && $response->message == 'Company added successfully') {
            $whatsAppMessage = "Perusahaan *$newCompanyName* berhasil mendaftar. Mohon untuk diperiksa kelengkapan datanya.";
            $phoneNumber = "6285946362394"; // Nomor yang menerima notifikasi
            $this->sendWhatsAppNotification($phoneNumber, $whatsAppMessage);
            $session->setFlashdata('success', 'Pendaftaran Berhasil, silakan login');
            return redirect()->to('company/login');
        } else {
            $session->setFlashdata('error', 'Pendaftaran gagal, pastikan data yang dimasukan benar!');
            return redirect()->to('company/register');
        }
    }

    // public function sendWhatsAppNotification($phoneNumber, $message)
    // {
    //     $client = \Config\Services::curlrequest();

    //     try {
    //         $response = $client->post('http://wa-api.arifrizqi.com/send-message', [
    //             'json' => [
    //                 'session' => 'sesisatu',
    //                 'to' => $phoneNumber,
    //                 'text' => $message
    //             ]
    //         ]);

    //         return json_decode($response->getBody())->success;
    //     } catch (\Exception $e) {
    //         log_message('error', 'Failed to send WhatsApp message: ' . $e->getMessage());
    //         return false;
    //     }
    // }
    public function sendWhatsAppNotification($phoneNumber, $message)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post('https://api.kuotavpn.com/api/create-message', [
                'form_params' => [
                    'appkey' => 'aeddea6e-6b28-43ac-bcfb-a6211783d45b',
                    'authkey' => 'mhuiWc2Aqhp12TB9tgqhVuGYeG6iT2iGSlFOsDzHel8f8KxXRY',
                    'to' => $phoneNumber,
                    'message' => $message
                ]
            ]);

            return json_decode($response->getBody())->success;
        } catch (\Exception $e) {
            log_message('error', 'Failed to send WhatsApp message: ' . $e->getMessage());
            return false;
        }
    }


    public function companyLogin()
    {

        if (!session()->get('loggedIn')) {
            return redirect()->to('company/login');
        }

        // Tampilkan halaman login jika belum login
        return view('company/vacancies');
    }

    public function vacancyApplicant()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('company/login');
        }

        $judul = [
            'title' => 'List Applicants'
        ];

        $model = new VacancyModel();
        $companyId = session()->get('userId'); // Pastikan userId sesuai dengan companyId
        $data = $model->vacancyApplicant($companyId);

        if ($data && $data->status == 'Success') {
            return view('company/applicant', array_merge($judul, ['applicants' => $data->vacancies]));
        } else {
            return view('company/applicant', ['applicants' => []]);
        }
    }

    public function vacancies()
    {
        // $session = session();
        // var_dump($session->get());
        // $companyId = $session->get('userId'); // Assumed userId is the companyId

        // $model = new VacancyModel();
        // $data['vacancies'] = $model->getVacancies($companyId);

        // return view('vacancies', $data);
        $judul = [
            'title' => 'My Vacancies'
        ];
        $model = new VacancyModel();
        $modelCompany = new CompanyModel();
        $companyId = session()->get('userId'); // Make sure this is set
        $dataCompany = $modelCompany->getCompanyById($companyId);
        $data = $model->getVacancies($companyId);

        // Debugging line
        // var_dump($data);

        if ($data && $data->status == 'Success') {
            return view('company/vacancies', array_merge($judul, ['vacancies' => $data->vacancies, 'companies' => $dataCompany->company]));
        } else {
            return view('company/vacancies', ['vacancies' => []]);
        }
    }

    public function company()
    {
        // $session = session();
        // var_dump($session->get());
        // $companyId = $session->get('userId'); // Assumed userId is the companyId

        // $model = new VacancyModel();
        // $data['vacancies'] = $model->getVacancies($companyId);

        // return view('vacancies', $data);
        if (!session()->get('loggedIn')) {
            return redirect()->to('company/login');
        }
        $model = new VacancyModel();
        $companyId = session()->get('userId'); // Make sure this is set

        $data = $model->getCompany($companyId);
        $judul = [
            'title' => 'My Company'
        ];

        // Debugging line
        // var_dump($data);

        if ($data && $data->status == 'Success') {
            return view('company/profile', array_merge($judul, ['company' => $data->company]));
        } else {
            return view('company/profile', ['company' => []]);
        }
    }

    public function editProfile($vacancyId)
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }

        $judul = [
            'title' => 'Edit Profile'
        ];

        $model = new CompanyModel();
        $userId = session()->get('userId');
        $sectorModel = new CompanySectorModel();

        $sector = $sectorModel->getOrderedSectors();

        $data = $model->getCompanyById($userId, $vacancyId);

        if ($data && $data->status == 'Success') {
            return view('company/company_edit', array_merge($judul, ['company' => $data->company, 'sector' => $sector]));
        } else {
            return view('company/company_edit', ['company' => []]);
        }
    }

    public function updateProfile($companyId) // Adjust the parameter here
    {
        $model = new CompanyModel();
        $data = $this->request->getPost(); // Get post data
        $response = $model->updateCompany($companyId, $data); // Pass companyId and data

        if ($response && $response->message == 'Success') {
            return redirect()->to('company/profile')->with('message', $response->message);
        } else {
            // Handle error
            return redirect()->back()->withInput()->with('error', 'Data berhasil diupdate');
        }
    }

    public function uploadLogo($companyId)
    {
        $model = new CompanyModel();
        $file = $this->request->getFile('logo');
        log_message('debug', 'Uploading logo for company ID: ' . $companyId);

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $uploadResponse = $model->uploadLogo($companyId, $file);
            if ($uploadResponse->message == 'Update Successful') {
                return redirect()->to('company/profile')->with('message', 'Logo updated successfully.');
            } else {
                return redirect()->back()->withInput()->with('error', $uploadResponse->message ?? 'Failed to upload logo');
            }
        } else {
            return redirect()->back()->withInput()->with('error', 'Invalid file or file upload error.');
        }
    }

    public function uploadAkta($companyId)
    {
        $model = new CompanyModel();
        $file = $this->request->getFile('akta');
        log_message('debug', 'Uploading akta for company ID: ' . $companyId);

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $uploadResponse = $model->uploadAkta($companyId, $file);
            if ($uploadResponse->message == 'Update Successful') {
                return redirect()->to('company/profile')->with('message', 'Akta updated successfully.');
            } else {
                return redirect()->back()->withInput()->with('error', $uploadResponse->message ?? 'Failed to upload Akta');
            }
        } else {
            return redirect()->back()->withInput()->with('error', 'Invalid file or file upload error.');
        }
    }

    public function addVacancy()
    {
        $model = new VacancyModel();
        $companyId = session()->get('userId'); // Pastikan ini sudah di-set
        var_dump($companyId);
        $placement_address = $this->request->getVar('placement_address');
        $description = $this->request->getVar('description');
        $salary = $this->request->getVar('salary');
        $id_interest = $this->request->getVar('id_interest');
        $skill_one = $this->request->getVar('skill_one');
        $skill_two = $this->request->getVar('skill_two');
        $job_type = $this->request->getVar('job_type');
        $deadline_time = $this->request->getVar('deadline_time');

        $result = $model->addVacancy($companyId, [
            "placement_address" => $placement_address,
            "description" => $description,
            "salary" => $salary,
            "id_interest" => $id_interest,
            "skill_one" => $skill_one,
            "skill_two" => $skill_two,
            "job_type" => $job_type,
            "deadline_time" => $deadline_time
        ]);

        if ($result && isset($result->message) && $result->message == 'Vacancy created successfully') {
            // Redirect or show success message
            return redirect()->to('company/vacancies')->with('success', '<b>Selamat!</b> Lowongan Berhasil Ditambah');
        } else {
            // Redirect or show error message
            return redirect()->to('company/vacancies')->with('error', '<b>Gagal!</b> Akun anda belum belum, aktif silakan hubungi admin@disnakertrans.serangkota.go.id');
        }
    }



    public function showAddVacancyForm()
    {
        $judul = [
            'title' => 'Add Vacancies'
        ];
        $interestModel = new InterestModel();
        $skilModel = new SkillsModel();
        $inter['interest'] = $interestModel->getInterest();
        $skil['skills'] = $skilModel->getSkills();
        return view('company/add_vacancy_form', array_merge($judul, $inter, $skil));
    }

    public function applicants($vacancyId)
    {
        $judul = [
            'title' => 'List Applicants'
        ];
        $model = new VacancyModel();
        $companyId = session()->get('userId'); // Ambil companyId dari session

        $data = $model->getApplicants($companyId, $vacancyId);

        if ($data) {
            return view('company/applicants', array_merge($judul, [
                'applicants' => $data,
                'companyId' => $companyId,
                'vacancyId' => $vacancyId // Memastikan ini juga di-pass ke view
            ]));
        } else {
            return view('company/applicants', [
                'applicants' => [],
                'companyId' => $companyId,
                'vacancyId' => $vacancyId
            ]);
        }
    }


    public function acceptApplicant($companyId, $vacancyId, $applicantId)
    {
        $model = new VacancyModel();
        $result = $model->acceptApplicant($companyId, $vacancyId, $applicantId);
        return redirect()->to('company/vacancies/applicants/' . $vacancyId); // Asumsi URL kembali ke daftar pelamar
    }

    public function rejectApplicant($companyId, $vacancyId, $applicantId)
    {
        $model = new VacancyModel();
        $result = $model->rejectApplicant($companyId, $vacancyId, $applicantId);
        return redirect()->to('company/vacancies/applicants/' . $vacancyId); // Asumsi URL kembali ke daftar pelamar
    }

    // public function handleApplicant($companyId, $vacancyId, $applicantId)
    // {
    //     $notes = $this->request->getPost('notes');
    //     $action = $this->request->getPost('action');
    //     $model = new VacancyModel();

    //     if ($action == 'accept') {
    //         $result = $model->acceptApplicant($companyId, $vacancyId, $applicantId, $notes);
    //     } else if ($action == 'reject') {
    //         $result = $model->rejectApplicant($companyId, $vacancyId, $applicantId, $notes);
    //     }

    //     return redirect()->to('company/vacancies/applicants/' . $vacancyId);
    // }

    public function handleApplicant($companyId, $vacancyId, $applicantId)
    {
        $notes = $this->request->getPost('notes');
        $action = $this->request->getPost('action');
        $applicantPhoneNumber = $this->request->getPost('applicant_phone_number');
        $model = new VacancyModel();
        $vacancy = $model->getVacancy($companyId, $vacancyId);

        // Pastikan data perusahaan diambil dari vacancy
        $companyName = $vacancy->company_name; // Sesuaikan dengan nama kolom yang sesuai
        $vacancyTitle = $vacancy->placement_address; // Sesuaikan dengan nama kolom yang sesuai

        if ($action == 'accept') {
            $result = $model->acceptApplicant($companyId, $vacancyId, $applicantId, $notes);
            $notificationMessage = "Selamat! Lamaran anda untuk posisi *$vacancyTitle* di perusahaan *$companyName* disetujui. Berikut adalah catatan yang diberikan perusahaan: \n$notes";
        } else if ($action == 'reject') {
            $result = $model->rejectApplicant($companyId, $vacancyId, $applicantId, $notes);
            $notificationMessage = "Mohon Maaf! Lamaran anda untuk posisi *$vacancyTitle* di perusahaan *$companyName* ditolak. Berikut adalah alasan yang diberikan perusahaan: \n$notes";
        }
        // Preprocess phone number (Replace 08 with 628)
        $preprocessedPhoneNumber = preg_replace('/^08/', '628', $applicantPhoneNumber);

        // Send notification with the model
        $model = new VacancyModel();
        $notificationSuccess = $model->sendWhatsAppNotification($preprocessedPhoneNumber, $notificationMessage);

        // Handle success/failure of notification

        return redirect()->to('company/vacancies/applicants/' . $vacancyId);
    }

    public function edit($vacancyId)
    {
        $judul = [
            'title' => 'Edit Vacancy'
        ];
        $model = new VacancyModel();
        $skillmodel = new SkillsModel();
        $interestmodel = new InterestModel();
        $interest = $interestmodel->getInterest();
        $skill = $skillmodel->getSkills();
        $companyId = session()->get('userId');
        $data = $model->getVacancy($companyId, $vacancyId);
        return view('company/edit_vacancy', array_merge($judul, ['vacancy' => $data, 'skill' => $skill, 'interest' => $interest]));
    }

    public function update($vacancyId)
    {
        $model = new VacancyModel();
        $companyId = session()->get('userId');
        $data = $this->request->getPost();
        $response = $model->updateVacancy($companyId, $vacancyId, $data);

        return redirect()->to('company/vacancies')->with('berhasilEdit', $response->message);
    }

    public function hapusVacancy($vacancyId)
    {
        $model = new CompanyModel();
        $companyId = session()->get('userId');
        try {
            $response = $model->deleteVacancyByCompany($companyId, $vacancyId);

            if ($response) {
                session()->setFlashdata('message', 'Data Berhasil Diupload');
            } else {
                session()->setFlashdata('hapus', 'Data Berhasil dihapus');
            }
        } catch (\Exception $e) {
            session()->setFlashdata('hapus', 'Lowongan sudah ada pelamar, tidak bisa dihapus!.');
            return redirect()->to('company/vacancies')->with('message', 'Error 500: Internal Server Error');
        }

        return redirect()->to('company/vacancies')->with('message', $response->message);
    }
}
