<?php
/**
 * Created by PhpStorm.
 * User: Kavand
 * Date: 3/7/2019
 * Time: 9:50 AM
 */

switch ($request['header-type']) {
    case 'add-acceptor-code':
        $state = ($DLA->DoCommand("INSERT INTO `app_acceptor_code_list` (`acceptor_id`, `acceptor_code`) VALUES ('{$request['id']}','{$request['ac']}')") ? "1" : "0");
        echo json_encode(array("state" => ($state ? "1" : "0"), 'id' => $request['id'], 'code' => $request['ac']));
        break;
    case 'add-acceptor-terminal':
        $query = "INSERT INTO `app_acceptor_terminal_list` (`acceptor_id`, `acceptor_code`, `acceptor_terminal`) VALUES ('{$request['id']}','{$request['ac']}','{$request['at']}')";
        $state = ($DLA->DoCommandID($query));
        echo json_encode(array("state" => ($state ? "1" : "0"), 'item_id' => $state, 'id' => $request['id'], 'code' => $request['ac'], 'terminal' => $request['at']));
        break;
    case 'remove-terminal':
        $state = ($DLA->DoCommand("DELETE FROM `app_acceptor_terminal_list` WHERE `ID`='{$request['id']}'") ? "1" : "0");
        echo json_encode(array("state" => ($state ? "1" : "0"), 'id' => $request['id']));
        break;
    case 'remove-acceptor-code':
        $state = false;
        if ($DLA->DoCommand("DELETE FROM `app_acceptor_terminal_list` WHERE (`acceptor_id`='{$request['id']}') AND (`acceptor_code`='{$request['code']}')")) {
            if ($DLA->DoCommand("DELETE FROM `app_acceptor_code_list` WHERE (`acceptor_id`='{$request['id']}') AND (`acceptor_code`='{$request['code']}')")) {
                $state = true;
            }
        }
        echo json_encode(
            array(
                "state" => ($state ? "1" : "0"),
                'id' => $request['id'],
                "code" => $request['code']
            )
        );
        break;
    case 'load-acceptor-code':
        $data = array();
        $select = $DLA->Select("SELECT `ID`,`acceptor_code`,`acceptor_id` FROM `app_acceptor_code_list` WHERE `acceptor_id`='{$request['id']}'");
        if ($select) {
            for ($i = 0; $i < count($select); $i += 1) {
                $row = $select[$i];
                $record = $DLA->Select("SELECT `ID`, `acceptor_terminal` FROM `app_acceptor_terminal_list` WHERE (`acceptor_id`='{$row['acceptor_id']}') AND (acceptor_code='{$row['acceptor_code']}')");
                $child = array();
                if ($record)
                    foreach ($record as $item) {
                        $child[] = array(
                            'ID' => $item['ID'],
                            'acceptor_terminal' => $item['acceptor_terminal']
                        );
                    }
                $data[] = array('ID' => $row['ID'], 'code' => $row['acceptor_code'], 'terminal' => $child);
            }
        }
        echo json_encode($data);
        break;
    default:
        echo 0;
        break;
}