<?php

use api\classes\API_inserve;

session_start();

require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_inserve.php";

$API_inserve = new API_inserve();
$API_inserve->setupConnection();

if ($API_inserve->request_method === 'POST' || $API_inserve->request_method === 'GET') {
    # Code below will retrieve all the companies and create or update it in the database

    $API_inserve->checkPermissions('customer-companies', 'RW');

    $allCompanies = [];
    $page = 1;

    do {
        $result = $API_inserve->companies($page);

        if (empty($result['data'])) {
            break;
        }

        foreach ($result['data'] as $item) {
            $allCompanies[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'debtor_code' => $item['debtor_code'],
                'archived_at' => $item['archived_at']
            ];
        }

        $page++;

    } while ($result['next_page_url'] !== null);

    foreach ($allCompanies as $company) {
        $source_uuid = $API_inserve->inserve_source_uuid;
        $company_id = $company['id'];
        $debtor_code = $company['debtor_code'];
        $company_name = $company['name'];
        $created_at = time();

        # Add or modify the company if it is not archived
        if ($company['archived_at'] == null) {
            $query = "INSERT INTO companies (source_uuid, company_source_id, company_source_id2, company_name, company_create_timestamp)
                VALUES (?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    company_name = VALUES(company_name),
                    company_source_id2 = VALUES(company_source_id2),
                    company_modified_timestamp = VALUES(company_create_timestamp)";
            $stmt = $API_inserve->prepareStatement($query);
            $stmt->bind_param('ssssi', $source_uuid, $company_id, $debtor_code, $company_name, $created_at);
            $API_inserve->executeStatement($stmt);
            $stmt->close();
        }
    }

    $API_inserve->apiOutput(200, ['success' => 'Sync is done successfully']);
}


