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

if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php"); 
    exit;
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="거래처리스트_' . date('Y-m-d') . '.csv"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

// BOM 추가 (Excel에서 한글 깨짐 방지)
echo "\xEF\xBB\xBF";

// CSV 헤더 (사업자번호, 상호, 대표자명, 거래처주소, 담당자이름, 이메일)
$headers = [
    '사업자번호',
    '상호',
    '대표자명',
    '거래처주소',
    '담당자이름',
    '이메일'
];

// 헤더 출력
$output = fopen('php://output', 'w');
fputcsv($output, $headers);

// 데이터 받기
$data = isset($_POST['data']) ? json_decode($_POST['data'], true) : [];

if (is_array($data) && count($data) > 0) {
    foreach ($data as $row) {
        $csvRow = [
            $row['vendor_code'] ?? '',
            $row['vendor_name'] ?? '',
            $row['representative_name'] ?? '',
            $row['address'] ?? '',
            $row['manager_name'] ?? '',
            $row['email'] ?? ''
        ];
        fputcsv($output, $csvRow);
    }
}

fclose($output);
exit;
