<?php

namespace App\Libraries\DBMigration\Process;

use CodeIgniter\Database\BaseConnection;

class ClientProcess implements MigrationProcessInterface
{
  private $db;
  public function __construct(BaseConnection $db)
  {
    $this->db = $db;
  }

  public function process(string $site, array $row, int $cnt): void
  {
    $temps = [];
    $temps['site'] = $site;
    $temps['user_uid'] = 1;
    $temps['role'] = $row['Client_Reseller'] == 30 ? "reseller" : "user";
    $temps['name'] = $row['Client_Name'];
    $temps['phone'] = empty($row['Client_Phone1']) ? "" : $row['Client_Phone1'];
    if (empty($temps['phone'])) {
      $temps['phone'] = empty($row['Client_Phone2']) ? "" : $row['Client_Phone2'];
    }
    $temps['email'] = empty($row['Client_EMail1']) ? "" : $row['Client_EMail1'];
    if (empty($temps['email'])) {
      $temps['email'] = empty($row['Client_EMail2']) ? "" : $row['Client_EMail2'];
    }
    $temps['history'] = nl2br($row['Client_Note']);
    $temps['account_balance'] = intval($row['Client_Money']);
    $temps['coupon_balance'] = 0;
    $temps['point_balance'] = 0;
    $temps['status'] = STATUS['AVAILABLE']; // Default status
    $temps['updated_at'] = empty($row['Client_Renew_date']) ? NULL : $row['Client_Renew_date'];
    if (!empty($row['Client_Receive_date'])) {
      $temps['created_at'] = $row['Client_Receive_date'];
    }
    if (!$this->db->table('clientinfo')->insert($temps)) {
      throw new \Exception($this->db->error()['message']);
    }
    echo "{$cnt} -> {$temps['name']} 고객완료.\n";
  }
}
