<?php
// pages/company_db.php — 기업 DB
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';

// ── CSV 다운로드/템플릿은 header 출력 전에 처리 ──
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    if (session_status() === PHP_SESSION_NONE) session_start();
    $db = (new Database())->getConnection();
    $search = trim($_GET['q'] ?? '');
    $fIndustry = $_GET['industry'] ?? '';
    $fField = $_GET['field'] ?? '';
    $fRoute = $_GET['contact_route'] ?? '';
    $where = "WHERE c.is_active=1"; $params = [];
    if ($search !== '') { $where .= " AND (c.company_name LIKE ? OR c.ceo_name LIKE ? OR c.contact_name LIKE ? OR c.contact_phone LIKE ? OR c.industry LIKE ? OR c.field LIKE ? OR c.phone LIKE ? OR c.mobile LIKE ? OR c.email LIKE ? OR c.website LIKE ? OR c.contact_route LIKE ?)"; $like="%{$search}%"; $params=[$like,$like,$like,$like,$like,$like,$like,$like,$like,$like,$like]; }
    if ($fIndustry) { $where .= " AND c.industry = ?"; $params[] = $fIndustry; }
    if ($fField) { $where .= " AND c.field = ?"; $params[] = $fField; }
    if ($fRoute) { $where .= " AND c.contact_route = ?"; $params[] = $fRoute; }
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="company_db_'.date('Ymd').'.csv"');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['업체명','대표자명','담당자명','담당자번호','업종','분야','대표전화','휴대폰','메일주소','홈페이지','컨택경로','등록자','등록일']);
    $allStmt = $db->prepare("SELECT c.*, s.name AS registered_name FROM company_db c LEFT JOIN staff s ON c.registered_by=s.staff_id {$where} ORDER BY c.created_at DESC");
    $allStmt->execute($params);
    while ($r = $allStmt->fetch()) {
        fputcsv($out, [$r['company_name'],$r['ceo_name'],$r['contact_name']??'',$r['contact_phone']??'',$r['industry'],$r['field'],$r['phone'],$r['mobile'],$r['email'],$r['website'],$r['contact_route'],$r['registered_name']??'',date('Y-m-d',strtotime($r['created_at']))]);
    }
    fclose($out); exit;
}
if (isset($_GET['template'])) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="company_db_template.csv"');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['업체명','대표자명','담당자명','담당자번호','업종','분야','대표전화','휴대폰','메일주소','홈페이지','컨택경로']);
    fputcsv($out, ['예시기업','홍길동','서비스업/개발업','소프트웨어 개발','02-1234-5678','010-1234-5678','info@example.com','https://www.example.com','전화영업']);
    fclose($out); exit;
}

// ── POST 처리 (header 전) ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (session_status() === PHP_SESSION_NONE) session_start();
    if (!isset($_SESSION['user_id'])) { header("Location: ".BASE_URL."index.php"); exit; }
    $db = (new Database())->getConnection();
    $user_role = $_SESSION['user_role'] ?? 'staff';
    $user_staff_id = $_SESSION['staff_id'] ?? 0;
    $message = '';

    if ($_POST['action'] === 'create') {
        try {
            $db->prepare("INSERT INTO company_db (company_name,ceo_name,contact_name,contact_phone,industry,field,phone,mobile,email,website,contact_route,registered_by,source_type) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)")
               ->execute([trim($_POST['company_name']),trim($_POST['ceo_name']??''),trim($_POST['contact_name']??''),trim($_POST['contact_phone']??''),trim($_POST['industry']??''),trim($_POST['field']??''),trim($_POST['phone']??''),trim($_POST['mobile']??''),trim($_POST['email']??''),trim($_POST['website']??''),trim($_POST['contact_route']??''),$user_staff_id,'수동등록']);
            writeAudit($db,'company_db',$db->lastInsertId(),'CREATE',['company_name'=>trim($_POST['company_name'])]);
            $message = '기업이 등록되었습니다.';
        } catch(PDOException $e) { $message = '오류: '.$e->getMessage(); }
        header("Location: ".BASE_URL."pages/company_db.php?msg=".urlencode($message)); exit;
    }
    if ($_POST['action'] === 'update') {
        $cid = (int)$_POST['company_id'];
        try {
            $db->prepare("UPDATE company_db SET company_name=?,ceo_name=?,contact_name=?,contact_phone=?,industry=?,field=?,phone=?,mobile=?,email=?,website=?,contact_route=? WHERE company_id=?")
               ->execute([trim($_POST['company_name']),trim($_POST['ceo_name']??''),trim($_POST['contact_name']??''),trim($_POST['contact_phone']??''),trim($_POST['industry']??''),trim($_POST['field']??''),trim($_POST['phone']??''),trim($_POST['mobile']??''),trim($_POST['email']??''),trim($_POST['website']??''),trim($_POST['contact_route']??''),$cid]);
            writeAudit($db,'company_db',$cid,'UPDATE',['company_name'=>trim($_POST['company_name'])]);
            $message = '기업 정보가 수정되었습니다.';
        } catch(PDOException $e) { $message = '오류: '.$e->getMessage(); }
        header("Location: ".BASE_URL."pages/company_db.php?msg=".urlencode($message)); exit;
    }
    if ($_POST['action'] === 'request_delete') {
        $cid = (int)$_POST['company_id']; $reason = trim($_POST['reason'] ?? '');
        if ($cid && $reason) {
            $dup = $db->prepare("SELECT COUNT(*) FROM company_delete_requests WHERE company_id=? AND status='대기'"); $dup->execute([$cid]);
            if ($dup->fetchColumn() > 0) {
                $message = '이미 삭제 요청이 접수된 기업입니다.';
            } else {
                try { $db->prepare("INSERT INTO company_delete_requests (company_id,requested_by,reason) VALUES(?,?,?)")->execute([$cid,$user_staff_id,$reason]);
                    writeAudit($db,'company_delete_requests',$db->lastInsertId(),'CREATE',['company_id'=>$cid,'reason'=>$reason]);
                    $message = '삭제 요청이 접수되었습니다.';
                } catch(PDOException $e) { $message = '오류: '.$e->getMessage(); }
            }
        } else { $message = '삭제 사유를 입력해주세요.'; }
        header("Location: ".BASE_URL."pages/company_db.php?msg=".urlencode($message)); exit;
    }
    if ($_POST['action'] === 'approve_delete' && in_array($user_role, ['sysadmin','ceo','manager'])) {
        $reqId = (int)$_POST['req_id']; $decision = $_POST['decision'] ?? '';
        if ($reqId && in_array($decision, ['승인','거절'])) {
            $db->prepare("UPDATE company_delete_requests SET status=?,reviewed_by=?,resolved_at=NOW() WHERE req_id=?")->execute([$decision,$user_staff_id,$reqId]);
            writeAudit($db,'company_delete_requests',$reqId,$decision,['decision'=>$decision]);
            if ($decision === '승인') {
                $cidStmt = $db->prepare("SELECT company_id FROM company_delete_requests WHERE req_id=?"); $cidStmt->execute([$reqId]);
                $companyId = $cidStmt->fetchColumn();
                if ($companyId) $db->prepare("UPDATE company_db SET is_active=0 WHERE company_id=?")->execute([$companyId]);
                $message = '삭제 승인 완료.';
            } else { $message = '삭제 요청이 거절되었습니다.'; }
        }
        header("Location: ".BASE_URL."pages/company_db.php?msg=".urlencode($message)); exit;
    }
    if ($_POST['action'] === 'excel_upload' && isset($_FILES['excel_file'])) {
        $file = $_FILES['excel_file']; $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['csv','tsv'])) { $message = 'CSV/TSV 파일만 가능합니다.'; }
        else {
            $handle = fopen($file['tmp_name'], 'r');
            if ($handle) {
                $sep = ($ext === 'tsv') ? "\t" : ",";
                $header = fgetcsv($handle, 0, $sep);
                if ($header) $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]);
                $colMap = ['업체명'=>'company_name','대표자명'=>'ceo_name','담당자명'=>'contact_name','담당자번호'=>'contact_phone','업종'=>'industry','분야'=>'field','대표전화'=>'phone','휴대폰'=>'mobile','메일주소'=>'email','홈페이지'=>'website','컨택경로'=>'contact_route'];
                $idxMap = [];
                foreach ($header as $i => $h) { $h = trim($h); if (isset($colMap[$h])) $idxMap[$colMap[$h]] = $i; }
                if (!isset($idxMap['company_name'])) { $message = '필수 컬럼 "업체명"이 없습니다.'; }
                else {
                    $cnt = 0;
                    $ins = $db->prepare("INSERT INTO company_db (company_name,ceo_name,contact_name,contact_phone,industry,field,phone,mobile,email,website,contact_route,registered_by,source_type) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    while (($row = fgetcsv($handle, 0, $sep)) !== false) {
                        $cn = trim($row[$idxMap['company_name']] ?? ''); if ($cn === '') continue;
                        $ins->execute([$cn,trim($row[$idxMap['ceo_name']??999]??''),trim($row[$idxMap['contact_name']??999]??''),trim($row[$idxMap['contact_phone']??999]??''),trim($row[$idxMap['industry']??999]??''),trim($row[$idxMap['field']??999]??''),trim($row[$idxMap['phone']??999]??''),trim($row[$idxMap['mobile']??999]??''),trim($row[$idxMap['email']??999]??''),trim($row[$idxMap['website']??999]??''),trim($row[$idxMap['contact_route']??999]??''),$user_staff_id,'엑셀등록']);
                        $cnt++;
                    }
                    fclose($handle); $message = "{$cnt}건 등록 완료.";
                }
            } else { $message = '파일 읽기 실패.'; }
        }
        header("Location: ".BASE_URL."pages/company_db.php?msg=".urlencode($message)); exit;
    }
}

// ── 헤더 출력 ──
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();
$user = currentUser();

// 필터용 고유값 조회
$industries = $db->query("SELECT DISTINCT industry FROM company_db WHERE is_active=1 AND industry!='' ORDER BY industry")->fetchAll(PDO::FETCH_COLUMN);
$fields = $db->query("SELECT DISTINCT field FROM company_db WHERE is_active=1 AND field!='' ORDER BY field")->fetchAll(PDO::FETCH_COLUMN);
$routes = $db->query("SELECT DISTINCT contact_route FROM company_db WHERE is_active=1 AND contact_route!='' ORDER BY contact_route")->fetchAll(PDO::FETCH_COLUMN);
$registerers = $db->query("SELECT DISTINCT s.staff_id, s.name FROM company_db c JOIN staff s ON c.registered_by=s.staff_id WHERE c.is_active=1 ORDER BY s.name")->fetchAll();

// 필터값
$search = trim($_GET['q'] ?? '');
$fIndustry = $_GET['industry'] ?? '';
$fField = $_GET['field'] ?? '';
$fRoute = $_GET['contact_route'] ?? '';
$fRegisterer = $_GET['registered_by'] ?? '';
$perPage = 50;
$page = max(1, (int)($_GET['page'] ?? 1));

$where = "WHERE c.is_active=1"; $params = [];
if ($search !== '') { $where .= " AND (c.company_name LIKE ? OR c.ceo_name LIKE ? OR c.contact_name LIKE ? OR c.contact_phone LIKE ? OR c.industry LIKE ? OR c.field LIKE ? OR c.phone LIKE ? OR c.mobile LIKE ? OR c.email LIKE ? OR c.website LIKE ? OR c.contact_route LIKE ? OR s.name LIKE ?)"; $like="%{$search}%"; $params=[$like,$like,$like,$like,$like,$like,$like,$like,$like,$like,$like,$like]; }
if ($fIndustry) { $where .= " AND c.industry = ?"; $params[] = $fIndustry; }
if ($fField) { $where .= " AND c.field = ?"; $params[] = $fField; }
if ($fRoute) { $where .= " AND c.contact_route = ?"; $params[] = $fRoute; }
if ($fRegisterer) { $where .= " AND c.registered_by = ?"; $params[] = $fRegisterer; }

$countStmt = $db->prepare("SELECT COUNT(*) FROM company_db c LEFT JOIN staff s ON c.registered_by=s.staff_id {$where}");
$countStmt->execute($params);
$totalCnt = (int)$countStmt->fetchColumn();
$totalPages = max(1, ceil($totalCnt / $perPage));
$offset = ($page - 1) * $perPage;

$stmt = $db->prepare("SELECT c.*, s.name AS registered_name FROM company_db c LEFT JOIN staff s ON c.registered_by=s.staff_id {$where} ORDER BY c.created_at DESC LIMIT {$perPage} OFFSET {$offset}");
$stmt->execute($params);
$list = $stmt->fetchAll();
$message = $_GET['msg'] ?? '';
$hasFilter = ($fIndustry || $fField || $fRoute || $fRegisterer);
?>

<div class="page-header">
    <h2>🏢 기업 DB</h2>
</div>

<?php if ($message): ?>
    <div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<!-- 템플릿 / 엑셀 등록 / 다운로드 -->
<div style="display:flex;justify-content:flex-end;gap:0.5rem;align-items:center;margin-bottom:1.5rem;">
    <a href="?template=1" class="btn btn-outline" style="font-size:14px;padding:0.45rem 0.85rem;">📥 템플릿</a>
    <button class="btn btn-outline" style="font-size:14px;padding:0.45rem 0.85rem;" onclick="document.getElementById('uploadModal').classList.add('show')">📤 엑셀 등록</button>
    <a href="?<?= http_build_query(array_merge($_GET, ['export'=>'csv'])) ?>" class="btn btn-outline" style="font-size:14px;padding:0.45rem 0.85rem;">⬇ 다운로드</a>
</div>

<!-- 필터 + 검색 + 버튼 통합 섹션 -->
<div class="card" style="margin-bottom:1.5rem;padding:0.85rem 1rem;">
    <form method="GET" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
        <select name="industry" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <option value="">업종 전체</option>
            <?php foreach ($industries as $v): ?>
                <option value="<?= htmlspecialchars($v) ?>" <?= $fIndustry===$v?'selected':'' ?>><?= htmlspecialchars($v) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="field" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <option value="">분야 전체</option>
            <?php foreach ($fields as $v): ?>
                <option value="<?= htmlspecialchars($v) ?>" <?= $fField===$v?'selected':'' ?>><?= htmlspecialchars($v) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="contact_route" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <option value="">컨택경로 전체</option>
            <?php foreach ($routes as $v): ?>
                <option value="<?= htmlspecialchars($v) ?>" <?= $fRoute===$v?'selected':'' ?>><?= htmlspecialchars($v) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="registered_by" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <option value="">등록자 전체</option>
            <?php foreach ($registerers as $r): ?>
                <option value="<?= $r['staff_id'] ?>" <?= $fRegisterer==$r['staff_id']?'selected':'' ?>><?= htmlspecialchars($r['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <div style="flex:1;"></div>
        <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="검색어를 입력하세요." class="company-search" style="width:300px;padding:0.45rem 0;background:transparent;border:none;border-bottom:1px solid var(--form-line-color,#333338);border-radius:0;color:var(--text-primary);font-size:14px;outline:none;" onfocus="this.style.borderBottomColor='var(--accent)'" onblur="this.style.borderBottomColor='var(--form-line-color,#333338)'">
        <button type="submit" class="btn btn-primary" style="padding:0.45rem 0.9rem;font-size:14px;">검색</button>
        <button type="button" class="btn btn-primary" onclick="document.getElementById('addCompModal').classList.add('show')" style="padding:0.45rem 0.9rem;font-size:14px;">+ 기업 등록</button>
        <?php if ($hasFilter): ?>
        <a href="company_db.php" class="btn btn-outline" style="padding:0.375rem 1rem;font-size:14px;">초기화</a>
        <?php endif; ?>
    </form>
</div>

<!-- 기업 목록 -->
<div class="card">
    <div class="card-header">
        <h3>기업 목록 (<?= number_format($totalCnt) ?>건)</h3>
    </div>
    <div class="table-wrap">
        <table>
            <thead><tr>
                <th>No</th><th>업체명</th><th>대표자명</th><th>담당자명</th><th>담당자번호</th><th>업종</th><th>분야</th>
                <th>대표전화</th><th>휴대폰</th><th>메일</th><th>홈페이지</th>
                <th>컨택경로</th><th>등록자</th><th>등록일</th><th>관리</th>
            </tr></thead>
            <tbody>
            <?php foreach ($list as $idx => $c): ?>
                <tr>
                    <td><?= ($page-1)*$perPage + $idx + 1 ?></td>
                    <td><strong><?= htmlspecialchars($c['company_name']) ?></strong></td>
                    <td><?= htmlspecialchars($c['ceo_name']) ?></td>
                    <td><?= htmlspecialchars($c['contact_name']??'') ?></td>
                    <td><?= htmlspecialchars($c['contact_phone']??'') ?></td>
                    <td><?= htmlspecialchars($c['industry']) ?></td>
                    <td><?= htmlspecialchars($c['field']) ?></td>
                    <td><?= htmlspecialchars($c['phone']) ?></td>
                    <td><?= htmlspecialchars($c['mobile']) ?></td>
                    <td><?= htmlspecialchars($c['email']) ?></td>
                    <td><?php if ($c['website']): ?>
                        <a href="<?= htmlspecialchars($c['website']) ?>" target="_blank" style="display:inline-block;background:var(--accent);color:var(--text-color,#EAEAEA);font-size:0.7rem;padding:0.15rem 0.5rem;border-radius:20px;text-decoration:none;line-height:1.4;"><?= htmlspecialchars(preg_replace('#^https?://(www\.)?#','', $c['website'])) ?></a>
                    <?php else: ?><span style="color:var(--text-tertiary);">-</span><?php endif; ?></td>
                    <td><?= htmlspecialchars($c['contact_route']) ?></td>
                    <td><?= htmlspecialchars($c['registered_name'] ?? '-') ?></td>
                    <td style="color:var(--text-tertiary);"><?= date('m/d', strtotime($c['created_at'])) ?></td>
                    <td>
                        <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;" onclick='openEditComp(<?= json_encode($c, JSON_UNESCAPED_UNICODE) ?>)'>✏️</button>
                        <button class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;color:var(--text-tertiary);" onclick="openDelComp(<?= $c['company_id'] ?>,'<?= htmlspecialchars(addslashes($c['company_name']),ENT_QUOTES) ?>')">🗑️</button>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($list)): ?>
                <tr><td colspan="13" style="text-align:center;padding:2rem;color:var(--text-tertiary);">데이터가 존재하지 않습니다.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($totalPages > 1): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:0.5rem;padding:1rem;">
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-right:0.5rem;">총 <?= number_format($totalCnt) ?>건 (<?= $page ?>/<?= $totalPages ?>)</span>
        <?php if ($page > 1): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$page-1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">‹ 이전</a>
        <?php endif; ?>
        <?php for ($p = max(1,$page-2); $p <= min($totalPages,$page+2); $p++): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$p])) ?>" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);border-radius:4px;text-decoration:none;<?= $p===$page?'background:var(--accent);color:var(--bg-color);font-weight:700;':'color:var(--text-secondary);' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
        <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$page+1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">다음 ›</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<?php
if (in_array($user['role'], ['sysadmin','ceo','manager'])) {
    $pendingDel = $db->query("SELECT dr.*, c.company_name, s.name AS requester_name FROM company_delete_requests dr LEFT JOIN company_db c ON dr.company_id=c.company_id LEFT JOIN staff s ON dr.requested_by=s.staff_id WHERE dr.status='대기' ORDER BY dr.created_at DESC")->fetchAll();
    if ($pendingDel):
?>
<div class="card" style="margin-top:1.25rem;">
    <div class="card-header"><h3>🗑️ 삭제 요청 대기 (<?= count($pendingDel) ?>건)</h3></div>
    <div class="table-wrap"><table>
        <thead><tr><th>요청자</th><th>기업명</th><th>사유</th><th>요청일</th><th>처리</th></tr></thead>
        <tbody>
        <?php foreach ($pendingDel as $pd): ?>
        <tr>
            <td><strong><?= htmlspecialchars($pd['requester_name']??'-') ?></strong></td>
            <td><?= htmlspecialchars($pd['company_name']??'(삭제됨)') ?></td>
            <td style="font-size:var(--fs-xs);max-width:200px;"><?= htmlspecialchars($pd['reason']) ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= date('m/d H:i', strtotime($pd['created_at'])) ?></td>
            <td style="white-space:nowrap;">
                <form method="POST" style="display:inline;"><input type="hidden" name="action" value="approve_delete"><input type="hidden" name="req_id" value="<?= $pd['req_id'] ?>"><input type="hidden" name="decision" value="승인">
                    <button type="submit" class="btn btn-sm btn-success" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;" onclick="return confirm('삭제를 승인하시겠습니까?')">승인</button></form>
                <form method="POST" style="display:inline;"><input type="hidden" name="action" value="approve_delete"><input type="hidden" name="req_id" value="<?= $pd['req_id'] ?>"><input type="hidden" name="decision" value="거절">
                    <button type="submit" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;">거절</button></form>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table></div>
</div>
<?php endif; } ?>

<!-- 기업 등록 모달 -->
<div class="modal-overlay" id="addCompModal">
    <div class="modal" style="max-width:580px;">
        <div class="modal-header"><h3>🏢 기업 등록</h3><button class="modal-close" onclick="document.getElementById('addCompModal').classList.remove('show')">&times;</button></div>
        <form method="POST"><input type="hidden" name="action" value="create">
            <div class="form-row"><div class="form-group"><label>업체명 <span class="required">*</span></label><input type="text" name="company_name" required placeholder="업체명"></div><div class="form-group"><label>대표자명</label><input type="text" name="ceo_name" placeholder="대표자명"></div></div>
            <div class="form-row"><div class="form-group"><label>담당자명</label><input type="text" name="contact_name" placeholder="담당자명"></div><div class="form-group"><label>담당자 번호</label><input type="text" name="contact_phone" placeholder="010-0000-0000"></div></div>
            <div class="form-row"><div class="form-group"><label>업종</label><input type="text" name="industry" placeholder="예: 서비스업"></div><div class="form-group"><label>분야</label><input type="text" name="field" placeholder="예: 소프트웨어 개발"></div></div>
            <div class="form-row"><div class="form-group"><label>대표전화</label><input type="text" name="phone" placeholder="02-1234-5678"></div><div class="form-group"><label>휴대폰</label><input type="text" name="mobile" placeholder="010-1234-5678"></div></div>
            <div class="form-row"><div class="form-group"><label>메일주소</label><input type="email" name="email" placeholder="info@company.com"></div><div class="form-group"><label>홈페이지</label><input type="url" name="website" placeholder="https://www.company.com"></div></div>
            <div class="form-group"><label>컨택경로</label><input type="text" name="contact_route" placeholder="지인 소개, 전화 영업, SNS 등"></div>
            <div class="btn-group mt-16"><button type="submit" class="btn btn-primary">등록</button><button type="button" class="btn btn-outline" onclick="document.getElementById('addCompModal').classList.remove('show')">취소</button></div>
        </form>
    </div>
</div>

<!-- 수정 모달 -->
<div class="modal-overlay" id="editCompModal">
    <div class="modal" style="max-width:580px;">
        <div class="modal-header"><h3>✏️ 기업 수정</h3><button class="modal-close" onclick="document.getElementById('editCompModal').classList.remove('show')">&times;</button></div>
        <form method="POST"><input type="hidden" name="action" value="update"><input type="hidden" name="company_id" id="ec_id">
            <div class="form-row"><div class="form-group"><label>업체명 <span class="required">*</span></label><input type="text" name="company_name" id="ec_name" required></div><div class="form-group"><label>대표자명</label><input type="text" name="ceo_name" id="ec_ceo"></div></div>
            <div class="form-row"><div class="form-group"><label>담당자명</label><input type="text" name="contact_name" id="ec_ctname"></div><div class="form-group"><label>담당자 번호</label><input type="text" name="contact_phone" id="ec_ctphone"></div></div>
            <div class="form-row"><div class="form-group"><label>업종</label><input type="text" name="industry" id="ec_industry"></div><div class="form-group"><label>분야</label><input type="text" name="field" id="ec_field"></div></div>
            <div class="form-row"><div class="form-group"><label>대표전화</label><input type="text" name="phone" id="ec_phone"></div><div class="form-group"><label>휴대폰</label><input type="text" name="mobile" id="ec_mobile"></div></div>
            <div class="form-row"><div class="form-group"><label>메일주소</label><input type="email" name="email" id="ec_email"></div><div class="form-group"><label>홈페이지</label><input type="url" name="website" id="ec_website"></div></div>
            <div class="form-group"><label>컨택경로</label><input type="text" name="contact_route" id="ec_route"></div>
            <div class="btn-group mt-16"><button type="submit" class="btn btn-primary">수정 저장</button><button type="button" class="btn btn-outline" onclick="document.getElementById('editCompModal').classList.remove('show')">취소</button></div>
        </form>
    </div>
</div>

<!-- 삭제 요청 모달 -->
<div class="modal-overlay" id="delCompModal">
    <div class="modal" style="max-width:420px;">
        <div class="modal-header"><h3>🗑️ 삭제 요청</h3><button class="modal-close" onclick="document.getElementById('delCompModal').classList.remove('show')">&times;</button></div>
        <form method="POST"><input type="hidden" name="action" value="request_delete"><input type="hidden" name="company_id" id="dc_id">
            <div style="margin-bottom:0.75rem;font-size:var(--fs-sm);color:var(--text-secondary);"><strong id="dc_name" style="color:var(--accent);"></strong> 삭제를 요청합니다.</div>
            <div class="form-group"><label>삭제 사유 <span class="required">*</span></label><textarea name="reason" rows="3" required placeholder="삭제 사유를 상세히 입력하세요"></textarea></div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);">시스템관리자 / 대표 / 관리자 승인 후 삭제됩니다.</div>
            <div class="btn-group mt-16"><button type="submit" class="btn btn-primary">삭제 요청</button><button type="button" class="btn btn-outline" onclick="document.getElementById('delCompModal').classList.remove('show')">취소</button></div>
        </form>
    </div>
</div>

<!-- 엑셀 업로드 모달 -->
<div class="modal-overlay" id="uploadModal">
    <div class="modal" style="max-width:480px;">
        <div class="modal-header"><h3>📤 엑셀 등록</h3><button class="modal-close" onclick="document.getElementById('uploadModal').classList.remove('show')">&times;</button></div>
        <form method="POST" enctype="multipart/form-data"><input type="hidden" name="action" value="excel_upload">
            <div class="form-group"><label>CSV 파일 선택</label>
                <input type="file" name="excel_file" accept=".csv,.tsv" required style="padding:0.5rem;background:var(--card-bg);border:1px solid var(--border-color);border-radius:6px;color:var(--text-primary);width:100%;">
                <div style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-top:0.25rem;">📥 <a href="?template=1" style="color:var(--accent);">템플릿 다운로드</a> 후 데이터를 채워 업로드하세요.</div>
            </div>
            <div class="btn-group mt-16"><button type="submit" class="btn btn-primary">업로드</button><button type="button" class="btn btn-outline" onclick="document.getElementById('uploadModal').classList.remove('show')">취소</button></div>
        </form>
    </div>
</div>

<script>
function openEditComp(c) {
    document.getElementById('ec_id').value=c.company_id; document.getElementById('ec_name').value=c.company_name||'';
    document.getElementById('ec_ceo').value=c.ceo_name||'';
    document.getElementById('ec_ctname').value=c.contact_name||''; document.getElementById('ec_ctphone').value=c.contact_phone||'';
    document.getElementById('ec_industry').value=c.industry||'';
    document.getElementById('ec_field').value=c.field||''; document.getElementById('ec_phone').value=c.phone||'';
    document.getElementById('ec_mobile').value=c.mobile||''; document.getElementById('ec_email').value=c.email||'';
    document.getElementById('ec_website').value=c.website||''; document.getElementById('ec_route').value=c.contact_route||'';
    document.getElementById('editCompModal').classList.add('show');
}
function openDelComp(id, name) {
    document.getElementById('dc_id').value=id; document.getElementById('dc_name').textContent=name;
    document.getElementById('delCompModal').classList.add('show');
}
</script>
<style>.company-search::placeholder{color:var(--form-placeholder,#555560);}</style>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
