<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
include '../lib/mydb.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'OPTIONS') {
    exit;
}

// 퍼미션 체크 (레벨 1 관리자만 접근 가능)
if (!isset($_SESSION['level']) || $_SESSION['level'] != '1') {
    echo json_encode(['success' => false, 'message' => '권한이 없습니다.']);
    exit;
}

$pdo = db_connect();
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

try {
    if (!$pdo) throw new Exception("Database connection failed.");

    // DB명이 정의되지 않았을 경우를 대비해 기본값 설정 혹은 mydb.php의 $DB 사용
    // 보통 mydb.php에서 $DB 변수를 제공한다고 가정
    if (!isset($DB)) {
        global $DB;
    }

    switch ($action) {
        case 'get_companies':
            // 모든 회사 가져오기 (파트너-자식 구조)
            $sql = "SELECT c.*, p.company_name as parent_name, p.barobill_user_id as parent_user_id 
                    FROM {$DB}.barobill_companies c 
                    LEFT JOIN {$DB}.barobill_companies p ON c.parent_id = p.id 
                    ORDER BY c.parent_id ASC, c.id ASC";
            $stmt = $pdo->query($sql);
            $companies = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $companies]);
            break;

        case 'save_company':
            // 회사 추가/수정
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            
            $company_name = $_POST['company_name'];
            $corp_num = $_POST['corp_num'];
            $barobill_user_id = $_POST['barobill_user_id'];
            $memo = $_POST['memo'];
            
            // 1. Find ID of 'cbx0913' (Parent)
            $parent_sql = "SELECT id FROM {$DB}.barobill_companies WHERE barobill_user_id = 'cbx0913' LIMIT 1";
            $stmt = $pdo->query($parent_sql);
            $parent_row = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // 만약 'cbx0913' 본인이면 parent_id는 NULL
            if ($barobill_user_id === 'cbx0913') {
                $parent_id = null;
            } else {
                // 부모가 있으면 그 ID, 없으면 NULL (혹은 에러처리)
                $parent_id = $parent_row ? $parent_row['id'] : null;
            }
            
            if ($id > 0) {
                $sql = "UPDATE {$DB}.barobill_companies SET 
                        parent_id = :parent_id, 
                        company_name = :company_name, 
                        corp_num = :corp_num, 
                        barobill_user_id = :barobill_user_id, 
                        memo = :memo 
                        WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            } else {
                $sql = "INSERT INTO {$DB}.barobill_companies (parent_id, company_name, corp_num, barobill_user_id, memo) 
                        VALUES (:parent_id, :company_name, :corp_num, :barobill_user_id, :memo)";
                $stmt = $pdo->prepare($sql);
            }

            $stmt->bindValue(':parent_id', $parent_id, PDO::PARAM_INT);
            $stmt->bindValue(':company_name', $company_name);
            $stmt->bindValue(':corp_num', $corp_num);
            $stmt->bindValue(':barobill_user_id', $barobill_user_id);
            $stmt->bindValue(':memo', $memo);
            
            if (!$stmt->execute()) {
                throw new Exception(implode(", ", $stmt->errorInfo()));
            }
            echo json_encode(['success' => true]);
            break;

        case 'delete_company':
            $id = intval($_POST['id']);
            $sql = "DELETE FROM {$DB}.barobill_companies WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            
            if (!$stmt->execute()) {
                throw new Exception(implode(", ", $stmt->errorInfo()));
            }
            echo json_encode(['success' => true]);
            break;

        case 'get_cards':
            $company_id = intval($_GET['company_id']);
            $sql = "SELECT * FROM {$DB}.company_cards WHERE company_id = :company_id ORDER BY id DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':company_id', $company_id, PDO::PARAM_INT);
            $stmt->execute();
            $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $cards]);
            break;

        case 'save_card':
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            $company_id = intval($_POST['company_id']);
            $card_company_code = $_POST['card_company_code'];
            $card_num = $_POST['card_num'];
            $web_id = $_POST['web_id'];
            $web_pwd = $_POST['web_pwd'];
            
            if ($id > 0) {
                $sql = "UPDATE {$DB}.company_cards SET 
                        card_company_code = :card_company_code, 
                        card_num = :card_num, 
                        web_id = :web_id, 
                        web_pwd = :web_pwd 
                        WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            } else {
                $sql = "INSERT INTO {$DB}.company_cards (company_id, card_company_code, card_num, web_id, web_pwd) 
                        VALUES (:company_id, :card_company_code, :card_num, :web_id, :web_pwd)";
                $stmt = $pdo->prepare($sql);
                $stmt->bindValue(':company_id', $company_id, PDO::PARAM_INT);
            }

            $stmt->bindValue(':card_company_code', $card_company_code);
            $stmt->bindValue(':card_num', $card_num);
            $stmt->bindValue(':web_id', $web_id);
            $stmt->bindValue(':web_pwd', $web_pwd);
            
            if (!$stmt->execute()) {
                throw new Exception(implode(", ", $stmt->errorInfo()));
            }
            echo json_encode(['success' => true]);
            break;
            
        case 'delete_card':
            $id = intval($_POST['id']);
            $sql = "DELETE FROM {$DB}.company_cards WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            
            if (!$stmt->execute()) {
                throw new Exception(implode(", ", $stmt->errorInfo()));
            }
            echo json_encode(['success' => true]);
            break;

        case 'get_accounts':
            $company_id = intval($_GET['company_id']);
            $sql = "SELECT * FROM {$DB}.company_accounts WHERE company_id = :company_id ORDER BY id DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':company_id', $company_id, PDO::PARAM_INT);
            $stmt->execute();
            $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $accounts]);
            break;

        case 'save_account':
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            $company_id = intval($_POST['company_id']);
            $bank_code = $_POST['bank_code'];
            $account_num = $_POST['account_num'];
            $account_pwd = $_POST['account_pwd'];
            
            if ($id > 0) {
                $sql = "UPDATE {$DB}.company_accounts SET 
                        bank_code = :bank_code, 
                        account_num = :account_num, 
                        account_pwd = :account_pwd 
                        WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            } else {
                $sql = "INSERT INTO {$DB}.company_accounts (company_id, bank_code, account_num, account_pwd) 
                        VALUES (:company_id, :bank_code, :account_num, :account_pwd)";
                $stmt = $pdo->prepare($sql);
                $stmt->bindValue(':company_id', $company_id, PDO::PARAM_INT);
            }

            $stmt->bindValue(':bank_code', $bank_code);
            $stmt->bindValue(':account_num', $account_num);
            $stmt->bindValue(':account_pwd', $account_pwd);
            
            if (!$stmt->execute()) {
                throw new Exception(implode(", ", $stmt->errorInfo()));
            }
            echo json_encode(['success' => true]);
            break;
            
        case 'delete_account':
            $id = intval($_POST['id']);
            $sql = "DELETE FROM {$DB}.company_accounts WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            
            if (!$stmt->execute()) {
                throw new Exception(implode(", ", $stmt->errorInfo()));
            }
            echo json_encode(['success' => true]);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
