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

class Setting extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        // Cek apakah user sudah login
        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }

        if (!check_permission('setting', 'can_view')) {
            show_error('Anda tidak memiliki izin untuk mengakses halaman ini.', 403);
        }
    }

    // ==========================
    // MAIN PAGE
    // ==========================
    public function index()
    {
        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        // Ambil config id=1
        $cfg = $this->db->get_where("config", ["id" => 1])->row();

        // Jika tidak ada data config
        $config = $cfg ?: $this->defaultConfig();

        // Ambil template pesan
        $template_pesan = $this->db
            ->order_by("id", "ASC")
            ->get("template_pesan")
            ->result();

        $data = [
            "active_menu"    => "pengaturan",
            "config"         => $config,
            "template_pesan" => $template_pesan
        ];

        $this->load->view('partials/header', $data);
        $this->load->view('setting/layout', $data);
        $this->load->view('partials/footer');
    }

    // =============================== 
    // DEFAULT CONFIG
    // ===============================
    private function defaultConfig()
    {
        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        return (object)[
            "nama_lembaga"      => "",
            "pimpinan_lembaga"  => "",
            "card_background"   => "",
            "card_orientation"  => "landscape",
            "wa_mode"           => "official",
            "wa_phone"          => "",
            "wa_phone_id"       => "",
            "wa_waba_id"        => "",
            "wa_access_token"   => "",
            "wa_endpoint"       => "",
            "wa_api_key"        => ""
        ];
    }

    // ===============================
    // 1. SIMPAN SETTING UMUM
    // ===============================
    public function save_umum()
    {
        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        $update = [
            "nama_lembaga"     => $this->input->post("nama_lembaga"),
            "pimpinan_lembaga" => $this->input->post("pimpinan_lembaga"),
            "updated_at"       => date("Y-m-d H:i:s")
        ];

        $this->db->where("id", 1)->update("config", $update);

        redirect("setting");
    }

    // ===============================
    // 2. SIMPAN CARD + UPLOAD BG
    // ===============================
    public function save_card()
    {

        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        $orientation = $this->input->post("card_orientation");
        $bg = null;

        // Jika ada upload file
        if (!empty($_FILES["card_background"]["name"])) {

            $config['upload_path']   = './uploads/card/';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['file_name']     = 'background_' . time();

            if (!is_dir('./uploads/card/')) {
                mkdir('./uploads/card/', 0777, true);
            }

            $this->load->library('upload', $config);

            if ($this->upload->do_upload('card_background')) {
                $file = $this->upload->data();
                $bg = "uploads/card/" . $file['file_name'];
            }
        }

        // Data update
        $data = [
            "card_orientation" => $orientation,
            "updated_at"       => date("Y-m-d H:i:s")
        ];

        // Jika ada gambar baru
        if ($bg !== null) {
            $data["card_background"] = $bg;
        }

        $this->db->where("id", 1)->update("config", $data);

        redirect("setting");
    }

    // ===============================
    // 3. SIMPAN SETTING WHATSAPP
    // ===============================
    public function save_whatsapp()
    {

        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        $mode = $this->input->post("wa_mode");

        $data = [
            "wa_mode"    => $mode,
            "updated_at" => date("Y-m-d H:i:s")
        ];

        if ($mode == "official") {

            $data["wa_phone"]        = $this->input->post("wa_phone");
            $data["wa_phone_id"]     = $this->input->post("wa_phone_id");
            $data["wa_waba_id"]      = $this->input->post("wa_waba_id");
            $data["wa_access_token"] = $this->input->post("wa_access_token");

            // Kosongkan unofficial
            $data["wa_endpoint"] = "";
            $data["wa_api_key"]  = "";

        } else {

            $data["wa_endpoint"] = $this->input->post("wa_endpoint");
            $data["wa_api_key"]  = $this->input->post("wa_api_key");

            // Kosongkan official
            $data["wa_phone"]        = "";
            $data["wa_phone_id"]     = "";
            $data["wa_waba_id"]      = "";
            $data["wa_access_token"] = "";
        }

        $this->db->where("id", 1)->update("config", $data);

        redirect("setting");
    }

    // ===============================
    // 4. UPDATE TEMPLATE PESAN
    // ===============================
    public function update_template_pesan()
    {

        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }

        $data = [
            "nama_template"  => $this->input->post("nama_template"),
            "isi_template" => $this->input->post("isi_template")
        ];

        $id = $this->input->post("id");

        $this->db->where("id", $id)->update("template_pesan", $data);

        redirect("setting");
    }

    public function cek_whatsapp_status()
    {

        if (!check_permission('setting', 'can_view')) {
            show_error('Tidak memiliki izin untuk melihat detail.', 403);
        }
        
        $config = $this->db->get_where("config", ["id" => 1])->row();

        if (!$config) {
            echo json_encode([
                "status" => "error",
                "img" => base_url("uploads/whatsapp/disconnect.png"),
                "msg" => "Config tidak ditemukan"
            ]);
            return;
        }

        // Fungsi bantu call API
        function callCurl($url, $fields)
        {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $url, 
                CURLOPT_RETURNTRANSFER => true, 
                CURLOPT_ENCODING => '', 
                CURLOPT_MAXREDIRS => 10, 
                CURLOPT_TIMEOUT => 0, 
                CURLOPT_FOLLOWLOCATION => true, 
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
                CURLOPT_CUSTOMREQUEST => 'GET', 
                CURLOPT_POSTFIELDS => $fields, 
                CURLOPT_HTTPHEADER => array( 'Content-Type: application/x-www-form-urlencoded' ),
            ]);
            $response = curl_exec($curl);
            curl_close($curl);
            return $response;
        }

        // 1. CEK STATUS
        $response = callCurl(
            $config->wa_endpoint . "getState",
            "apiKey=" . $config->wa_api_key
        );

        $data = json_decode($response, true);

        if (!$data || !isset($data['results']['state'])) {
            echo json_encode([
                "status" => "error",
                "img" => base_url('uploads/whatsapp/disconnect.png'),
                "msg" => "Gagal membaca respon server WA",
                "data" => $data,
                "url_key" => $config->wa_endpoint . ' ' . $config->wa_api_key
            ]);
            return;
        }

        $state = $data['results']['state'];

        // ==========================================================
        // 1. CONNECTED → tampilkan gambar connected
        // ==========================================================
        if ($state == "CONNECTED") {
            echo json_encode([
                "status" => "CONNECTED",
                "img" => base_url('uploads/whatsapp/connect.png')
            ]);
            return;
        }

        // ==========================================================
        // 2. SERVICE_OFF → tampilkan disconnect + mulai service
        // ==========================================================
        if ($state == "SERVICE_OFF") {

            // Mulai service
            callCurl(
                $config->wa_endpoint . "serviceStart",
                "apiKey=" . $config->wa_api_key
            );

            echo json_encode([
                "status" => "SERVICE_OFF",
                "img" => base_url('uploads/whatsapp/disconnect.png')
            ]);
            return;
        }

        // ==========================================================
        // 3. SERVICE_SCAN → ambil QR
        // ==========================================================
        if ($state == "SERVICE_SCAN") {

            $responseQR = callCurl(
                $config->wa_endpoint . "getQR",
                "apiKey=" . $config->wa_api_key
            );

            $qrData = json_decode($responseQR, true);

            if (!isset($qrData['results']['qrString'])) {
                echo json_encode([
                    "status" => "SERVICE_SCAN",
                    "img" => base_url('uploads/whatsapp/map_loader.gif')
                ]);
                return;
            }

            echo json_encode([
                "status" => "SERVICE_SCAN",
                "img" => $qrData['results']['qrString']
            ]);
            return;
        }

        // ==========================================================
        // 4. STATUS LAIN → tampilkan loader
        // ==========================================================
        echo json_encode([
            "status" => "UNKNOWN",
            "img" => base_url('uploads/whatsapp/map_loader.gif')
        ]);
    }

}
