<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Exception;

class PushCustomersToIntercom extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'customers:pushToIntercom';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Push customers to Intercom';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    
    public function __construct()
    {
        parent::__construct();
        
    }

    private function postToInterCom($url, $params){
        try {
            $postData = json_encode($params);
            $postHeader = [
                'Authorization:Bearer ' . config('app.intercomApiSecret'),
                'Accept: application/json',
                'Intercom-Version: 2.3',
                'content-type: application/json'
            ];
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $postHeader);
            $content = curl_exec($curl);
            curl_close($curl);
            $content = json_decode($content, true);
            if(isset($content['errors']) && count($content['errors'])){
                return ['success' => false, 'message' => $content['errors']];
            }
            return ['success' => true, 'data' => $content];
    
        } catch (Exception $e) {  
            return ['success' => false, 'message' => $e->getMessage()];  
        }
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {        
        $customers = User::all();
        if ($this->confirm('Do you wish to push '. $customers->count() . ' customers?', true)) {
            foreach($customers as $customer){
                $phone = preg_replace('/\D+/', '', $customer->phone_number ?? $customer->cell_number);
                $params = [
                    'name' => $customer->getName(),
                    'email' => $customer->getEmail(),
                    'signed_up_at' => strtotime($customer->created_at),
                    'type' => 'user',
                ];
                if(strlen($phone)){
                    $params['phone'] = '+' . $phone;
                }
                if($customer->mailing_address_line1){
                    $params['location'] = [
                        'type' => 'location',
                        'country' => $customer->mailing_address_country,
                        'region' => $customer->mailing_address_state . ', ' . $customer->mailing_address_line1 . ', ' .  $customer->mailing_address_line2,
                        'city' => $customer->mailing_address_city
                    ];
                }

                $response = $this->postToInterCom('https://api.intercom.io/contacts', $params);
                if($response['success']){
                    $this->info('Added ID: ' . $customer->id . ' | ' . $customer->displayName() );
                }else{
                    $this->error('Failed ID: ' . $customer->id . ' | ' . $customer->displayName() . ' | ERROR: ' . @$response['message'][0]['code'] . ' | ' . @$response['message'][0]['message']);
                }
            }

            $this->info('Completed!');
            
        }else{
            $this->error('Aborted');
        }
    }
}
