<?php
require FCPATH . "vendor/ripcord/ripcord.php";
require FCPATH . "vendor/ripcord/ripcord_client.php";

class Odoo extends MY_Controller
{
  var $db_odoo, $url, $username, $uid, $model, $password, $common;

  function __construct()
  {
    parent::__construct();
    $this->url = "http://odoo.sismedika.com";
    $this->db_odoo = "odoo16_sismedika";
    $this->username = "admin@sismedika.com";
    $this->password = "duD#Z36qH5ctmRRD";
    $this->common = ripcord::client("{$this->url}/xmlrpc/2/common");
    $this->uid = $this->common->authenticate($this->db_odoo, $this->username, $this->password, array());
    $this->model = ripcord::client("{$this->url}/xmlrpc/2/object");
    $this->db->query("use one_support");
  }
  function get_implementation($project_id = 70, $date = "")
  {
    if ($date == "") $date = date("Y-m-d");
    $sdate = $date . "  00:00:01";
    $edate = $date . "  23:59:59";
    $arg = array();
    $kwarg = array(
      "limit" => 10,
      "offset" => 0,
      "order" => "",
      "count_limit" => 11,
      "fields" => [
        "id",
        "name",
        "description",
      ],
      //"domain"=>[["stage_id","ilike","implementation"]] 
      // "domain"
    );
    $resp = $this->model->execute_kw(
      $this->db_odoo,
      $this->uid,
      $this->password,
      "project.task",
      "web_search_read",
      array(array(
        "&",
        ["display_project_id", "=", $project_id],
        "&",
        ["date_last_stage_update", ">=", $sdate],
        "&",
        ["date_last_stage_update", "<=", $edate],
        ["stage_id", "ilike", "implementation"]
      )),
      $kwarg
    );
    $arr_ticket = [];
    if (isset($resp["records"])) {
      foreach ($resp["records"] as $r) {
        $desc = $r["description"];
        $name = $r["name"];
        $id = $r["id"];
        $tiket = "";
        if (preg_match("/ No. Tiket  : <b>(.+)<\/b><br> Cabang/", $desc, $match)) {
          $tiket = $match[1];
          if (in_array($tiket,$arr_ticket)) {
            echo date("Y-m-d H:i:s") . " Ticket # $tiket duplicate \n";
            continue;
          }
          $arr_ticket[]= $tiket;
        }
        if ($tiket != "") {
          $rec = $this->get_ticketing($tiket);
          if ($rec["TicketingStatus"] != "IMPLEMENTATION") {
            $ticketID = $rec["TicketingID"];
            $sender = $rec["TicketingSender"];
            $cabang = $rec["M_BranchName"];
            $hasil = "";
            if (preg_match("/(Hasil.*:.+)/", $desc, $match)) {
              $hasil = strip_tags($match[1]);
              $hasil = str_replace("&nbsp;","",$hasil);
            }
            $impl_msg = "
Pengirim  :  $sender
No. Tiket : $tiket
Issue     : $name            
Cabang    : $cabang
Status    : Selesai
$hasil
            
Silahkan di cek kembali
Terima Kasih\n";
            echo date("Y-m-d H:i:s") . " Done Ticket # $tiket from $sender \n";
            $this->wa_to_sasone_done($impl_msg);
            $this->update_ticketing($ticketID, "IMPLEMENTATION", $ticketID);
            sleep(2);
          }
        }
      }
    }
  }

  function get_message($taskID)
  {
    $arg = [
      "thread_id" => $taskID,
      "thread_model" => "project_task",
      "limit" => 30
    ];
    $resp = $this->model->execute_kw(
      $this->db_odoo,
      $this->uid,
      $this->password,
      "mail.thread",
      "read",
      array($arg)
    );
    print_r($resp);
  }
  function wa_to_sasone_done(
    $msg
  ) {
    $this->load->library("Wa_sas");
    //$hp = "6287823783747";
    //$hp="6282113702602-1584412485@g.us";
    //bisone supporter
    $hp="6281328282909-1583223560@g.us";
    $resp = $this->wa_sas->send_message($hp, $msg, true);
  }
  function update_ticketing($ticketID, $status, $taskID)
  {
    $sql = "update ticketing set TicketingStatus = ?,
    TicketingOdooTaskID=?
    where ticketingID = ?";
    $qry = $this->db->query($sql, [$status, $taskID, $taskID]);
    if (!$qry) {
      echo "Error update ticketing $ticketID\n";
      exit;
    }
    echo $this->db->last_query() . "\n";
  }
  function get_ticketing($tiket)
  {
    $sql = "select TicketingID,TicketingStatus ,
    M_BranchName, TicketingSender
    from 
    ticketing 
    join m_branch on TicketingM_BranchCode = M_BranchCode 
    and TicketingNumber = ? 
    ";
    $qry = $this->db->query($sql, [$tiket]);
    if (!$qry) {
      echo "Error get ticketing $tiket\n";
      exit;
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "Error get ticketing $tiket\n";
      exit;
    }
    return $rows[0];
  }
  function create_ts()
  {
    $prm = $this->sys_input;
    $date = $prm["date"];
    $time = $prm["time"];
    $employee_id = $prm["employee_id"];
    $task_id = $prm["task_id"];
    $project_id = $prm["project_id"];
    $description = $prm["description"];

    $arg = array(
      "name" => $description,
      "date" => $date,
      "unit_amount" => $time,
      "user_id" => $this->uid,
      "task_id" => $task_id,
      "project_id" => $project_id,
      "employee_id" => $employee_id
    );

    $resp = $this->model->execute_kw(
      $this->db_odoo,
      $this->uid,
      $this->password,
      "account.analytic.line",
      "create",
      array($arg)
    );
    print_r($resp);
    if (!is_numeric($resp)) {
      echo json_encode(["status" => "ERR", "message" => json_encode($resp)]);
    } else {
      echo json_encode(
        [
          "status" => "OK",
          "ts_id" => $resp
        ]
      );
    }
  }
  function create_task()
  {
    $prm = $this->sys_input;
    $title = $prm["title"];
    $description = $prm["description"];
    $project_id  = $prm["project_id"];
    if ($project_id == "") $project_id  = 70;
    $images = $prm["images"];
    if (is_array($images)) {
      foreach ($images as $img) {
        $description .= "<br/>" .
          "<img class=\"img-fluid\" src=\"$img\">";
      }
    }
    $users = $prm["users"];
    if ($users == "") {
      $users = [
        44,
        41,
        42
      ];
    }
    $arg = array(
      "sun" => $this->bool_day("sun"),
      "mon" => $this->bool_day("mon"),
      "tue" => $this->bool_day("tue"),
      "wed" => $this->bool_day("wed"),
      "thu" => $this->bool_day("thu"),
      "fri" => $this->bool_day("fri"),
      "sat" => $this->bool_day("sat"),
      "recurrence_id" => false,
      "parent_id" => false,
      "company_id" => 1,
      "stage_id" => 443,
      "personal_stage_type_id" => false,
      "recurrence_update" => "this",
      "priority" => "0",
      "name" => "$title",
      "kanban_state" => "normal",
      "project_id" => $project_id,
      "display_project_id" => false,
      "milestone_id" => false,
      "user_ids" => [
        [
          6,
          false,
          $users
        ]
      ],
      "active" => true,
      "partner_id" => false,
      "partner_phone" => false,
      "date_deadline" => false,
      "tag_ids" => [
        [
          6,
          false,
          []
        ]
      ],
      "task_properties" => [],
      "description" => $description,
      "planned_hours" => 0,
      "timesheet_ids" => [],
      "child_ids" => [],
    );
    $resp = $this->model->execute_kw(
      $this->db_odoo,
      $this->uid,
      $this->password,
      "project.task",
      "create",
      array($arg)
    );
    if (!is_numeric($resp)) {
      echo json_encode(["status" => "ERR", "message" => json_encode($resp)]);
    } else {
      echo json_encode(
        [
          "status" => "OK",
          "task_id" => $resp
        ]
      );
    }
  }
  function bool_day($inp_dow)
  {
    $dow = strtolower(date("D", strtotime("now")));
    if ($inp_dow == $dow) return true;
    return false;
  }
}
