<?php

/*
 * Copyright 2019 Netsyms Technologies.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

use InvoiceNinja\Config as NinjaConfig;
use InvoiceNinja\Models\Client as NinjaClient;

if (!empty($SETTINGS["apis"]["invoiceninja"]["token"])) {
    // Use InvoiceNinja for clients
    try {
        NinjaConfig::setURL($SETTINGS["apis"]["invoiceninja"]["url"]);
        NinjaConfig::setToken($SETTINGS["apis"]["invoiceninja"]["token"]);
        NinjaConfig::setPerPage(9999); // https://github.com/invoiceninja/sdk-php/issues/21
    } catch (Exception $ex) {
        if ($SETTINGS['debug']) {
            echo $ex->getTraceAsString();
        }
        sendError("Unable to load InvoiceNinja API:\n" . $ex->getMessage());
    }

    class Clients {

        public static function getAll(): array {
            try {
                $clients = NinjaClient::all();
            } catch (Exception $ex) {
                if ($SETTINGS['debug']) {
                    echo $ex->getTraceAsString();
                }
                sendError("Unable to get InvoiceNinja client list:\n" . $ex->getMessage());
            }
            $list = [];
            foreach ($clients as $client) {
                $list[] = new Client($client->id, false, $client->display_name);
            }
            return $list;
        }

        /**
         * Search clients for fields containing $query
         * @param string $query
         * @return \Client Array of Clients
         */
        public static function search(string $query) {
            try {
                $clients = NinjaClient::all();
            } catch (Exception $ex) {
                if ($SETTINGS['debug']) {
                    echo $ex->getTraceAsString();
                }
                sendError("Unable to get InvoiceNinja client list:\n" . $ex->getMessage());
            }

            $query = strtolower(trim($query));

            $results = [];

            $fields = ["name", "display_name", "address1", "work_phone", "private_notes", "public_notes", "website", "shipping_address1"];
            $contactfields = ["first_name", "last_name", "email", "phone"];
            foreach ($clients as $client) {
                $match = false;
                $clientarr = (array)$client;
                foreach ($fields as $f) {
                    if (strpos(strtolower($clientarr[$f]), $query) !== FALSE) {
                        $c = new Client($client->id, false, $client->display_name);
                        $results[] = $c;
                        $match = true;
                        continue 2;
                    }
                }
                foreach ($client->contacts as $con) {
                    $conarr = (array)$con;
                    foreach ($contactfields as $f) {
                        if (strpos(strtolower($conarr[$f]), $query) !== FALSE) {
                            $c = new Client($client->id, false, $client->display_name);
                            $results[] = $c;
                            $match = true;
                            continue 3;
                        }
                    }
                }
            }

            return $results;
        }

        public static function getAllAsIDNameArray(): array {
            $clients = Clients::getAll();
            $arr = [];
            foreach ($clients as $c) {
                $arr[$c->getID()] = $c->getName();
            }
            return $arr;
        }

        public static function getClient($id): Client {
            return new Client($id, false);
        }

        public static function areLocal(): bool {
            return false;
        }

    }

} else {

    // Use internal client table
    class Clients {

        public static function getAll(): array {
            global $database;
            $clients = $database->select("clients", ["clientid"]);
            $list = [];
            foreach ($clients as $client) {
                $list[] = new Client($client['clientid'], true);
            }
            return $list;
        }

        public static function search(string $query) {
            $results = $database->select("clients", ["clientid"], ["OR" => [
                "name[~]" => $query,
                "phone[~]" => $query,
                "email[~]" => $query,
                "billingaddress[~]" => $query,
                "mailingaddress[~]" => $query,
                "publicnotes[~]" => $query,
                "privatenotes[~]" => $query
            ]]);

            $clients = [];
            foreach ($results as $r) {
                $clients[] = new Client($r["clientid"], true);
            }
            return $clients;
        }

        public static function getClient($id): Client {
            global $database;
            return new Client($id, true);
        }

        public static function areLocal(): bool {
            return true;
        }

    }

}