#!/usr/bin/php
<?php
// System Script: Contact Lookup
// Input: JSON argument from argv[1]; uses _cid_num (auto-injected by cpbx-ai)
// Output: JSON with contact details from phonebook, or not_found status

require_once('/usr/share/ombutel/www/includes/cli.php');

use ombutel\api;

$input = isset($argv[1]) ? $argv[1] : '{}';
$args = json_decode($input, true);
if (!is_array($args)) {
	echo json_encode(array('status' => 'error', 'error' => 'Invalid JSON input'));
	exit(1);
}

$callerid = isset($args['_cid_num']) ? trim($args['_cid_num']) : '';
if ($callerid === '') {
	echo json_encode(array('status' => 'error', 'error' => 'caller number not available'));
	exit(1);
}

$fields = array('phone', 'alt_phone', 'mobile');
$contacts = array();

foreach ($fields as $field) {
	$result = api::invoke('find_contact', null, array($field => $callerid));
	if ($result->status !== 'success') {
		$message = isset($result->message) ? $result->message : 'find_contact failed';
		echo json_encode(array('status' => 'error', 'error' => $message));
		exit(1);
	}
	foreach ($result->data as $contact) {
		$contacts[$contact->contact_id] = $contact;
	}
}

ksort($contacts);

if (empty($contacts)) {
	echo json_encode(array('status' => 'not_found', 'callerid' => $callerid));
	exit(0);
}

$contact = reset($contacts);

echo json_encode(array(
	'status' => 'found',
	'callerid' => $callerid,
	'first_name' => $contact->first_name,
	'second_name' => $contact->second_name,
	'last_name' => $contact->last_name,
	'organization' => $contact->organization,
	'phone' => $contact->phone,
	'alt_phone' => $contact->alt_phone,
	'mobile' => $contact->mobile,
	'email' => $contact->email,
	'job_title' => $contact->job_title,
	'location' => $contact->location,
));
