<?php
// pages/sales.php — 협찬 실적 입력 (SALES_DB)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';

// POST 처리 (header 출력 전에 redirect 처리)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    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' && in_array($user_role, ['team_leader','manager','ceo','sysadmin'])) {
        try {
            $stmt = $db->prepare("INSERT INTO sales
                (staff_id, company_name, program_name, episode, contract_date, filming_date, broadcast_date,
                 revenue, cost, net_profit, stage, confirm_type, memo, sale_month)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $rev = (int)$_POST['revenue'];
            $cst = (int)$_POST['cost'];
            $cdate = $_POST['contract_date'] ?: null;
            $stmt->execute([
                $_POST['staff_id'],
                trim($_POST['company_name']),
                trim($_POST['program_name']),
                trim($_POST['episode']),
                $cdate,
                $_POST['filming_date'] ?: null,
                $_POST['broadcast_date'] ?: null,
                $rev,
                $cst,
                $rev - $cst,
                $_POST['stage'],
                $_POST['confirm_type'],
                trim($_POST['memo']),
                $cdate ? date('Y-m', strtotime($cdate)) : null,
            ]);
            $newSaleId = $db->lastInsertId();
            // ── 영업 보고서 탭 데이터 저장 → 기업 DB 자동 누적 ──
            $rptCompany = trim($_POST['rpt_company_name'] ?? '');
            if ($rptCompany !== '') {
                $db->exec("CREATE TABLE IF NOT EXISTS sales_report (report_id INT AUTO_INCREMENT PRIMARY KEY,sale_id INT DEFAULT NULL,staff_id INT NOT NULL,company_name VARCHAR(100) NOT NULL,ceo_name VARCHAR(50) DEFAULT '',industry VARCHAR(100) DEFAULT '',field VARCHAR(100) DEFAULT '',phone VARCHAR(30) DEFAULT '',mobile VARCHAR(30) DEFAULT '',email VARCHAR(100) DEFAULT '',website VARCHAR(200) DEFAULT '',contact_route VARCHAR(200) DEFAULT '',call_notes TEXT DEFAULT NULL COMMENT '통화내용',created_at DATETIME DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $db->prepare("INSERT INTO sales_report (sale_id,staff_id,company_name,ceo_name,contact_name,contact_phone,industry,field,phone,mobile,email,website,contact_route,call_notes,check_date) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute([$newSaleId,$_POST['staff_id'],$rptCompany,trim($_POST['rpt_ceo_name']??''),trim($_POST['rpt_contact_name']??''),trim($_POST['rpt_contact_phone']??''),trim($_POST['rpt_industry']??''),trim($_POST['rpt_field']??''),trim($_POST['rpt_phone']??''),trim($_POST['rpt_mobile']??''),trim($_POST['rpt_email']??''),trim($_POST['rpt_website']??''),trim($_POST['rpt_contact_route']??''),trim($_POST['rpt_call_notes']??''),($_POST['rpt_check_date']??'')?:null]);
                $newReportId = $db->lastInsertId();
                $db->exec("CREATE TABLE IF NOT EXISTS company_db (company_id INT AUTO_INCREMENT PRIMARY KEY,company_name VARCHAR(100) NOT NULL,ceo_name VARCHAR(50) DEFAULT '',industry VARCHAR(100) DEFAULT '',field VARCHAR(100) DEFAULT '',phone VARCHAR(30) DEFAULT '',mobile VARCHAR(30) DEFAULT '',email VARCHAR(100) DEFAULT '',website VARCHAR(200) DEFAULT '',contact_route VARCHAR(200) DEFAULT '',registered_by INT DEFAULT NULL,source_type ENUM('영업보고서','엑셀등록','수동등록') DEFAULT '수동등록',source_report_id INT DEFAULT NULL,is_active TINYINT(1) DEFAULT 1,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $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,source_report_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute([$rptCompany,trim($_POST['rpt_ceo_name']??''),trim($_POST['rpt_contact_name']??''),trim($_POST['rpt_contact_phone']??''),trim($_POST['rpt_industry']??''),trim($_POST['rpt_field']??''),trim($_POST['rpt_phone']??''),trim($_POST['rpt_mobile']??''),trim($_POST['rpt_email']??''),trim($_POST['rpt_website']??''),trim($_POST['rpt_contact_route']??''),$_POST['staff_id'],'영업보고서',$newReportId]);
            }
            $message = '실적이 등록되었습니다.';
            writeAudit($db,'sales',$newSaleId,'INSERT',['company_name'=>trim($_POST['company_name']??''),'revenue'=>$_POST['revenue']??0]);
        } catch(PDOException $e) {
            $message = '오류: ' . $e->getMessage();
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }

    // 영업 보고서 수정 요청
    if ($_POST['action'] === 'request_report_edit') {
        $reportId = (int)($_POST['report_id'] ?? 0);
        $reason = trim($_POST['reason'] ?? '');
        if ($reportId && $reason) {
            $editData = json_encode([
                'company_name'=>trim($_POST['rpt_company_name']??''),'ceo_name'=>trim($_POST['rpt_ceo_name']??''),
                'contact_name'=>trim($_POST['rpt_contact_name']??''),'contact_phone'=>trim($_POST['rpt_contact_phone']??''),
                'industry'=>trim($_POST['rpt_industry']??''),'field'=>trim($_POST['rpt_field']??''),
                'phone'=>trim($_POST['rpt_phone']??''),'mobile'=>trim($_POST['rpt_mobile']??''),
                'email'=>trim($_POST['rpt_email']??''),'website'=>trim($_POST['rpt_website']??''),
                'contact_route'=>trim($_POST['rpt_contact_route']??''),'call_notes'=>trim($_POST['rpt_call_notes']??''),
                'check_date'=>($_POST['rpt_check_date']??'')?:null,
            ], JSON_UNESCAPED_UNICODE);
            $db->exec("CREATE TABLE IF NOT EXISTS report_edit_request (req_id INT AUTO_INCREMENT PRIMARY KEY,report_id INT NOT NULL,requested_by INT NOT NULL,edit_data TEXT,reason VARCHAR(500) DEFAULT '',status ENUM('대기','승인','거절') DEFAULT '대기',reviewed_by INT DEFAULT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,resolved_at DATETIME DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $db->prepare("INSERT INTO report_edit_request (report_id,requested_by,edit_data,reason) VALUES(?,?,?,?)")->execute([$reportId,$user_staff_id,$editData,$reason]);
            // 알림
            try {
                $admins = $db->query("SELECT user_id FROM user_account WHERE user_role IN('sysadmin','ceo','manager') AND is_active=1")->fetchAll(PDO::FETCH_COLUMN);
                $userName = $_SESSION['name'] ?? '';
                foreach ($admins as $aid) {
                    $db->prepare("INSERT INTO notifications (user_id,message,link) VALUES(?,?,?)")->execute([$aid,"📝 {$userName}님이 영업보고서 수정을 요청했습니다.",BASE_URL.'pages/sales.php']);
                }
            } catch(Exception $e) {}
            $message = '보고서 수정 요청이 접수되었습니다. 승인 후 반영됩니다.';
            writeAudit($db,'report_edit_request',$db->lastInsertId(),'INSERT',['report_id'=>$reportId,'reason'=>$reason]);
        } else { $message = '수정 사유를 입력해주세요.'; }
        header("Location: ".BASE_URL."pages/sales.php?msg=".urlencode($message)); exit;
    }

    // 영업 보고서 수정 승인/거절
    if ($_POST['action'] === 'approve_report_edit' && in_array($user_role, ['sysadmin','ceo','manager'])) {
        $reqId = (int)($_POST['req_id'] ?? 0);
        $decision = $_POST['decision'] ?? '';
        if ($reqId && in_array($decision, ['승인','거절'])) {
            $db->prepare("UPDATE report_edit_request SET status=?,reviewed_by=?,resolved_at=NOW() WHERE req_id=?")->execute([$decision,$user_staff_id,$reqId]);
            if ($decision === '승인') {
                $reqData = $db->prepare("SELECT * FROM report_edit_request WHERE req_id=?"); $reqData->execute([$reqId]); $req = $reqData->fetch();
                if ($req) {
                    $ed = json_decode($req['edit_data'], true);
                    $db->prepare("UPDATE sales_report SET company_name=?,ceo_name=?,industry=?,field=?,phone=?,mobile=?,email=?,website=?,contact_route=?,call_notes=? WHERE report_id=?")
                       ->execute([$ed['company_name']??'',$ed['ceo_name']??'',$ed['industry']??'',$ed['field']??'',$ed['phone']??'',$ed['mobile']??'',$ed['email']??'',$ed['website']??'',$ed['contact_route']??'',$ed['call_notes']??'',$req['report_id']]);
                    // company_db도 동기 업데이트
                    try { $db->prepare("UPDATE company_db SET company_name=?,ceo_name=?,industry=?,field=?,phone=?,mobile=?,email=?,website=?,contact_route=? WHERE source_report_id=?")
                       ->execute([$ed['company_name']??'',$ed['ceo_name']??'',$ed['industry']??'',$ed['field']??'',$ed['phone']??'',$ed['mobile']??'',$ed['email']??'',$ed['website']??'',$ed['contact_route']??'',$req['report_id']]); } catch(Exception $e) {}
                }
                $message = '보고서 수정이 승인되어 반영되었습니다.';
                writeAudit($db,'report_edit_request',$reqId,'승인',['report_id'=>$req['report_id']??0]);
            } else { $message = '보고서 수정 요청이 거절되었습니다.';
                writeAudit($db,'report_edit_request',$reqId,'거절'); }
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=".urlencode($message)); exit;
    }

    if ($_POST['action'] === 'update') {
        try {
            $saleId = (int)$_POST['sale_id'];
            $rev = (int)$_POST['revenue'];
            $cst = (int)$_POST['cost'];
            $cdate = $_POST['contract_date'] ?: null;
            $check = $db->prepare("SELECT staff_id FROM sales WHERE sale_id=?"); $check->execute([$saleId]); $owner = $check->fetchColumn();
            if (in_array($user_role, ['sysadmin','ceo','manager'])) {
                $handler = trim($_POST['handler_name'] ?? '');
                $db->prepare("UPDATE sales SET company_name=?, program_name=?, episode=?, contract_date=?, filming_date=?, broadcast_date=?, revenue=?, cost=?, net_profit=?, stage=?, confirm_type=?, memo=?, sale_month=?, handler_name=? WHERE sale_id=?")
                   ->execute([trim($_POST['company_name']), trim($_POST['program_name']), trim($_POST['episode']), $cdate, $_POST['filming_date']?:null, $_POST['broadcast_date']?:null, $rev, $cst, $rev-$cst, $_POST['stage'], $_POST['confirm_type'], trim($_POST['memo']), $cdate?date('Y-m',strtotime($cdate)):null, $handler, $saleId]);
                try { $db->prepare("UPDATE sales_report SET handler_name=? WHERE sale_id=?")->execute([$handler, $saleId]); } catch(Exception $e) {}
                $message = '실적이 수정되었습니다.';
            } else { $message = '수정 권한이 없습니다.'; }
        } catch(PDOException $e) { $message = '오류: '.$e->getMessage(); }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }

    if ($_POST['action'] === 'delete' && in_array($user_role, ['sysadmin','ceo','manager'])) {
        $saleId = (int)($_POST['sale_id'] ?? 0);
        if ($saleId) {
            $db->prepare("DELETE FROM sales WHERE sale_id=?")->execute([$saleId]);
            $message = '실적이 삭제되었습니다.';
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }

    if ($_POST['action'] === 'request_edit') {
        $saleId = (int)($_POST['sale_id'] ?? 0);
        if ($saleId) {
            $db->exec("CREATE TABLE IF NOT EXISTS edit_request (req_id INT AUTO_INCREMENT PRIMARY KEY, sale_id INT NOT NULL, requested_by INT NOT NULL, edit_data TEXT, reason VARCHAR(200) DEFAULT '', status ENUM('대기','승인','거절') DEFAULT '대기', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, resolved_at DATETIME DEFAULT NULL)");
            $editData = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            $db->prepare("INSERT INTO edit_request (sale_id, requested_by, edit_data, reason) VALUES(?,?,?,?)")->execute([$saleId, $user_staff_id, $editData, trim($_POST['edit_reason'] ?? '')]);
            $message = '수정 요청이 접수되었습니다. 시스템 관리자 승인 후 반영됩니다.';
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }

    if ($_POST['action'] === 'approve_edit' && in_array($user_role, ['sysadmin','ceo','manager'])) {
        $reqId = (int)($_POST['req_id'] ?? 0);
        $decision = $_POST['decision'] ?? '';
        if ($reqId && in_array($decision, ['승인','거절'])) {
            $db->prepare("UPDATE edit_request SET status=?, resolved_at=NOW() WHERE req_id=?")->execute([$decision, $reqId]);
            if ($decision === '승인') {
                $reqData = $db->prepare("SELECT * FROM edit_request WHERE req_id=?"); $reqData->execute([$reqId]); $req = $reqData->fetch();
                if ($req) {
                    $ed = json_decode($req['edit_data'], true);
                    $rev = (int)($ed['revenue']??0); $cst = (int)($ed['cost']??0);
                    $cdate = $ed['contract_date'] ?: null;
                    $db->prepare("UPDATE sales SET company_name=?, program_name=?, episode=?, contract_date=?, filming_date=?, broadcast_date=?, revenue=?, cost=?, net_profit=?, stage=?, confirm_type=?, memo=?, sale_month=? WHERE sale_id=?")
                       ->execute([trim($ed['company_name']??''), trim($ed['program_name']??''), trim($ed['episode']??''), $cdate, $ed['filming_date']?:null, $ed['broadcast_date']?:null, $rev, $cst, $rev-$cst, $ed['stage']??'계약', $ed['confirm_type']??'확정', trim($ed['memo']??''), $cdate?date('Y-m',strtotime($cdate)):null, $req['sale_id']]);
                }
                $message = '수정 요청이 승인되어 반영되었습니다.';
            } else {
                $message = '수정 요청이 거절되었습니다.';
            }
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }

    if ($_POST['action'] === 'request_delete') {
        $saleId = (int)($_POST['sale_id'] ?? 0);
        if ($saleId) {
            $db->exec("CREATE TABLE IF NOT EXISTS delete_request (req_id INT AUTO_INCREMENT PRIMARY KEY, sale_id INT NOT NULL, requested_by INT NOT NULL, reason VARCHAR(200) DEFAULT '', status ENUM('대기','승인','거절') DEFAULT '대기', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, resolved_at DATETIME DEFAULT NULL)");
            $db->prepare("INSERT INTO delete_request (sale_id, requested_by, reason) VALUES(?,?,?)")->execute([$saleId, $user_staff_id, trim($_POST['reason'] ?? '')]);
            $message = '삭제 요청이 접수되었습니다. 시스템 관리자 승인 후 삭제됩니다.';
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }

    if ($_POST['action'] === 'approve_delete' && in_array($user_role, ['sysadmin','ceo','manager'])) {
        $reqId = (int)($_POST['req_id'] ?? 0);
        $decision = $_POST['decision'] ?? '';
        if ($reqId && in_array($decision, ['승인','거절'])) {
            $db->prepare("UPDATE delete_request SET status=?, resolved_at=NOW() WHERE req_id=?")->execute([$decision, $reqId]);
            if ($decision === '승인') {
                $saleId = $db->prepare("SELECT sale_id FROM delete_request WHERE req_id=?"); $saleId->execute([$reqId]);
                $sid = $saleId->fetchColumn();
                if ($sid) $db->prepare("DELETE FROM sales WHERE sale_id=?")->execute([$sid]);
                $message = '삭제 요청이 승인되어 실적이 삭제되었습니다.';
            } else {
                $message = '삭제 요청이 거절되었습니다.';
            }
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=" . urlencode($message));
        exit;
    }
    // ── 처리내역(댓글) 관리 ──
    if ($_POST['action'] === 'add_comment') {
        $saleId = (int)($_POST['sale_id']??0); $content = trim($_POST['content']??'');
        if ($saleId && $content) {
            $db->exec("CREATE TABLE IF NOT EXISTS sale_comments (comment_id INT AUTO_INCREMENT PRIMARY KEY,sale_id INT NOT NULL,staff_id INT NOT NULL,content TEXT NOT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $db->prepare("INSERT INTO sale_comments (sale_id,staff_id,content) VALUES(?,?,?)")->execute([$saleId,$user_staff_id,$content]);
            $message = '처리내역이 등록되었습니다.';
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=".urlencode($message)); exit;
    }
    if ($_POST['action'] === 'update_comment') {
        $cid = (int)($_POST['comment_id']??0); $content = trim($_POST['content']??'');
        if ($cid && $content) {
            $own = $db->prepare("SELECT staff_id FROM sale_comments WHERE comment_id=?"); $own->execute([$cid]); $oid=$own->fetchColumn();
            if ($oid==$user_staff_id || in_array($user_role,['sysadmin','ceo','manager'])) {
                $db->prepare("UPDATE sale_comments SET content=? WHERE comment_id=?")->execute([$content,$cid]);
                $message = '처리내역이 수정되었습니다.';
            }
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=".urlencode($message)); exit;
    }
    if ($_POST['action'] === 'delete_comment') {
        $cid = (int)($_POST['comment_id']??0);
        if ($cid) {
            $own = $db->prepare("SELECT staff_id FROM sale_comments WHERE comment_id=?"); $own->execute([$cid]); $oid=$own->fetchColumn();
            if ($oid==$user_staff_id || in_array($user_role,['sysadmin','ceo','manager'])) {
                $db->prepare("DELETE FROM sale_comments WHERE comment_id=?")->execute([$cid]);
                $message = '처리내역이 삭제되었습니다.';
            }
        }
        header("Location: ".BASE_URL."pages/sales.php?msg=".urlencode($message)); exit;
    }
}

// 이제 header 출력
require_once __DIR__ . '/../includes/header.php';

$db = (new Database())->getConnection();
// 빈 stage를 미진행으로 업데이트
try { $db->exec("UPDATE sales SET stage='미진행' WHERE stage IS NULL OR stage=''"); } catch(Exception $e) {}
$user = currentUser();
$perm = getMenuPerm($db, 'sales', $user['role']);
// 관리자/대표/시스템관리자는 항상 전체 조회
if (in_array($user['role'], ['sysadmin','ceo','manager'])) {
    $perm['view_scope'] = 'all';
    $perm['can_create'] = 1;
    $perm['can_edit'] = 1;
    $perm['can_delete'] = 1;
}

// 처리자 마스터 테이블 + handler_name 컬럼 보장
$db->exec("CREATE TABLE IF NOT EXISTS handler_master (handler_id INT AUTO_INCREMENT PRIMARY KEY, staff_id INT DEFAULT NULL, handler_name VARCHAR(50) NOT NULL, sort_order INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
try{$db->query("SELECT handler_name FROM sales LIMIT 0");}catch(Exception $e){try{$db->exec("ALTER TABLE sales ADD COLUMN handler_name VARCHAR(50) DEFAULT '' COMMENT '처리자'");}catch(Exception $e2){}}
try{$db->query("SELECT handler_name FROM sales_report LIMIT 0");}catch(Exception $e){try{$db->exec("ALTER TABLE sales_report ADD COLUMN handler_name VARCHAR(50) DEFAULT '' COMMENT '처리자'");}catch(Exception $e2){}}
// 관리자/대표/시스템관리자 목록으로 처리자 목록 생성
$handlerList = $db->query("SELECT ua.staff_id, st.name FROM user_account ua JOIN staff st ON ua.staff_id=st.staff_id WHERE ua.user_role IN('manager','ceo','sysadmin') AND ua.is_active=1 ORDER BY st.name")->fetchAll();

// 담당자 목록 (드롭다운용)
$staffList = $db->query("SELECT staff_id, name, grade, team, email FROM staff WHERE is_active=1 ORDER BY name")->fetchAll();

// 필터
$filterYear = $_GET['year'] ?? date('Y');
$filterMonth = $_GET['month'] ?? '';
$filterStaff = $_GET['staff_id'] ?? '';
$filterStage = $_GET['stage'] ?? '';
$filterTeam = $_GET['team'] ?? '';
$filterConfirm = $_GET['confirm_type'] ?? '';
$filterCheckDate = $_GET['check_date'] ?? '';
$filterHandler = $_GET['handler'] ?? '';

// 실적 목록 조회
$sql = "SELECT s.*, st.name AS staff_name, st.grade, st.team, st.email,
        IF(st.email='미기재','⚠ 이메일 등록 필요','') AS email_warn,
        sr.report_id, sr.company_name AS rpt_company, sr.ceo_name AS rpt_ceo,
        sr.contact_name AS rpt_contact_name, sr.contact_phone AS rpt_contact_phone,
        sr.industry AS rpt_industry, sr.field AS rpt_field, sr.phone AS rpt_phone,
        sr.mobile AS rpt_mobile, sr.email AS rpt_email, sr.website AS rpt_website,
        sr.contact_route AS rpt_route, sr.call_notes AS rpt_call_notes,
        sr.check_date AS rpt_check_date, sr.handler_name AS rpt_handler_name
FROM sales s
JOIN staff st ON s.staff_id = st.staff_id
LEFT JOIN sales_report sr ON sr.sale_id = s.sale_id
WHERE 1=1";
$params = [];

// 보기 범위 (menu_role_permission 연동)
if ($perm['view_scope'] === 'own') {
    $sql .= " AND s.staff_id = ?";
    $params[] = $user['staff_id'];
} elseif ($perm['view_scope'] === 'team') {
    $myTeam = $db->prepare("SELECT team FROM staff WHERE staff_id=?");
    $myTeam->execute([$user['staff_id']]); $myTeamName = $myTeam->fetchColumn();
    if ($myTeamName) { $sql .= " AND st.team = ?"; $params[] = $myTeamName; }
}
// 'all' = 전체 조회
if ($filterYear) { $sql .= " AND (YEAR(s.contract_date) = ? OR s.contract_date IS NULL)"; $params[] = $filterYear; }
if ($filterMonth) { $sql .= " AND s.sale_month = ?"; $params[] = $filterMonth; }
if ($filterStaff) { $sql .= " AND s.staff_id = ?"; $params[] = $filterStaff; }
if ($filterStage) { $sql .= " AND s.stage = ?"; $params[] = $filterStage; }
if ($filterTeam) { $sql .= " AND st.team = ?"; $params[] = $filterTeam; }
if ($filterConfirm) { $sql .= " AND s.confirm_type = ?"; $params[] = $filterConfirm; }
if ($filterCheckDate) { $sql .= " AND sr.check_date = ?"; $params[] = $filterCheckDate; }
if ($filterHandler) { $sql .= " AND s.handler_name = ?"; $params[] = $filterHandler; }
$sql .= " ORDER BY CASE WHEN s.confirm_type='확정' THEN 0 ELSE 1 END ASC, sr.check_date DESC, s.contract_date DESC, s.sale_id DESC";

// 페이지네이션용 카운트
$countSql = "SELECT COUNT(*) FROM sales s JOIN staff st ON s.staff_id = st.staff_id LEFT JOIN sales_report sr ON sr.sale_id = s.sale_id WHERE 1=1";
$countParams = [];
if ($perm['view_scope'] === 'own') { $countSql .= " AND s.staff_id = ?"; $countParams[] = $user['staff_id']; }
elseif ($perm['view_scope'] === 'team' && isset($myTeamName) && $myTeamName) { $countSql .= " AND st.team = ?"; $countParams[] = $myTeamName; }
if ($filterYear) { $countSql .= " AND (YEAR(s.contract_date) = ? OR s.contract_date IS NULL)"; $countParams[] = $filterYear; }
if ($filterMonth) { $countSql .= " AND s.sale_month = ?"; $countParams[] = $filterMonth; }
if ($filterStaff) { $countSql .= " AND s.staff_id = ?"; $countParams[] = $filterStaff; }
if ($filterStage) { $countSql .= " AND s.stage = ?"; $countParams[] = $filterStage; }
if ($filterTeam) { $countSql .= " AND st.team = ?"; $countParams[] = $filterTeam; }
if ($filterConfirm) { $countSql .= " AND s.confirm_type = ?"; $countParams[] = $filterConfirm; }
if ($filterCheckDate) { $countSql .= " AND sr.check_date = ?"; $countParams[] = $filterCheckDate; }
if ($filterHandler) { $countSql .= " AND s.handler_name = ?"; $countParams[] = $filterHandler; }
$countStmt = $db->prepare($countSql);
$countStmt->execute($countParams);
$totalCnt = (int)$countStmt->fetchColumn();
$perPage = 20;
$page = max(1, (int)($_GET['page'] ?? 1));
$totalPages = max(1, ceil($totalCnt / $perPage));
$offset = ($page - 1) * $perPage;
$sql .= " LIMIT $perPage OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$salesList = $stmt->fetchAll();

// 처리내역(댓글) 로드
$db->exec("CREATE TABLE IF NOT EXISTS sale_comments (comment_id INT AUTO_INCREMENT PRIMARY KEY,sale_id INT NOT NULL,staff_id INT NOT NULL,content TEXT NOT NULL,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
$commentMap = [];
$saleIds = array_column($salesList, 'sale_id');
if ($saleIds) {
    $inP = implode(',', array_fill(0, count($saleIds), '?'));
    $cmStmt = $db->prepare("SELECT sc.*, st.name AS author_name FROM sale_comments sc LEFT JOIN staff st ON sc.staff_id=st.staff_id WHERE sc.sale_id IN($inP) ORDER BY sc.created_at ASC");
    $cmStmt->execute($saleIds);
    foreach ($cmStmt->fetchAll() as $c) $commentMap[$c['sale_id']][] = $c;
}
// 녹음파일 로드 (sale_id → report_id 매핑)
$callFileMapBySale = [];
$callFileMapByReport = [];
if ($saleIds) {
    try {
        $inP2 = implode(',', array_fill(0, count($saleIds), '?'));
        $cfStmt = $db->prepare("SELECT rcf.*, sr.sale_id, sr.report_id AS sr_report_id FROM report_call_files rcf INNER JOIN sales_report sr ON rcf.report_id=sr.report_id WHERE sr.sale_id IN($inP2) ORDER BY rcf.created_at ASC");
        $cfStmt->execute($saleIds);
        foreach ($cfStmt->fetchAll() as $cf) {
            $callFileMapBySale[$cf['sale_id']][] = $cf;
            $callFileMapByReport[$cf['report_id']][] = $cf;
        }
    } catch(Exception $e) {}
}

// 중복 체크용 목록
$dupCheck = $db->query("SELECT staff_id, company_name, episode, COUNT(*) AS cnt
    FROM sales GROUP BY staff_id, company_name, episode HAVING cnt > 1")->fetchAll();
$dupKeys = [];
foreach ($dupCheck as $d) {
    $dupKeys[$d['staff_id'].'-'.$d['company_name'].'-'.$d['episode']] = true;
}

// 월 목록, 년도 목록, 팀 목록
$months = $db->query("SELECT DISTINCT sale_month FROM sales ORDER BY sale_month DESC")->fetchAll(PDO::FETCH_COLUMN);
$salesYears = $db->query("SELECT DISTINCT YEAR(contract_date) FROM sales ORDER BY 1 DESC")->fetchAll(PDO::FETCH_COLUMN);
if (!$salesYears) $salesYears = [date('Y')];
$teamList = $db->query("SELECT team_name FROM team_master WHERE is_active=1 AND team_name NOT IN('경영진','경영지원','오너','시스템') ORDER BY team_name")->fetchAll(PDO::FETCH_COLUMN);

$message = $_GET['msg'] ?? '';
?>

<div class="page-header">
    <h2>💰 실적 검토</h2>
</div>

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

<!-- 필터 -->
<div class="card" style="margin-bottom:1rem;padding:0.75rem 1rem;">
    <form method="GET" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
        <select name="year" onchange="this.form.submit()" class="dash-filter" style="width:7rem;">
            <?php foreach ($salesYears as $y): ?>
            <option value="<?= $y ?>" <?= $filterYear==$y?'selected':'' ?>><?= $y ?>년</option>
            <?php endforeach; ?>
        </select>

        <select name="month" onchange="this.form.submit()" class="dash-filter" style="width:9rem;">
            <option value="">월 전체</option>
            <?php foreach ($months as $m): ?>
                <option value="<?= $m ?>" <?= $filterMonth === $m ? 'selected' : '' ?>><?= $m ?></option>
            <?php endforeach; ?>
        </select>

        <?php if (in_array($user['role'], ['manager','ceo','sysadmin'])): ?>
        <select name="team" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">팀 전체</option>
            <?php foreach ($teamList as $t): ?>
                <option value="<?= $t ?>" <?= $filterTeam === $t ? 'selected' : '' ?>><?= htmlspecialchars($t) ?></option>
            <?php endforeach; ?>
        </select>

        <select name="staff_id" onchange="this.form.submit()" class="dash-filter" style="width:10rem;">
            <option value="">담당자 전체</option>
            <?php foreach ($staffList as $s): ?>
                <option value="<?= $s['staff_id'] ?>" <?= $filterStaff == $s['staff_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php endif; ?>

        <select name="stage" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">단계 전체</option>
            <?php foreach (['미진행','리드','제안','계약','촬영','방송완료'] as $st): ?>
                <option value="<?= $st ?>" <?= $filterStage === $st ? 'selected' : '' ?>><?= $st ?></option>
            <?php endforeach; ?>
        </select>

        <select name="confirm_type" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">확정/예상 전체</option>
            <option value="확정" <?= $filterConfirm==='확정'?'selected':'' ?>>확정</option>
            <option value="예상" <?= $filterConfirm==='예상'?'selected':'' ?>>예상</option>
        </select>

        <select name="handler" onchange="this.form.submit()" class="dash-filter" style="width:8rem;">
            <option value="">처리자 전체</option>
            <?php foreach($handlerList as $hl):?><option value="<?=htmlspecialchars($hl['name'])?>" <?=$filterHandler===$hl['name']?'selected':''?>><?=htmlspecialchars($hl['name'])?></option><?php endforeach;?>
        </select>

        <span style="position:relative;display:inline-block;width:9rem;"><input type="date" name="check_date" value="<?=htmlspecialchars($filterCheckDate)?>" onchange="this.style.color='';this.form.submit()" class="dash-filter" style="width:100%;<?=$filterCheckDate?'':'color:transparent;'?>" onfocus="this.style.color=''" onblur="if(!this.value)this.style.color='transparent'"><?php if(!$filterCheckDate):?><span style="position:absolute;left:0.625rem;top:50%;transform:translateY(-50%);font-size:var(--fs-xs);color:var(--text-tertiary);pointer-events:none;">진행확인일</span><?php endif;?></span>

        <?php if ($filterMonth || $filterStaff || $filterStage || $filterTeam || $filterConfirm || $filterHandler || $filterCheckDate): ?>
        <a href="sales.php" class="btn btn-outline" style="padding:0.375rem 1rem;font-size:var(--fs-xs);">초기화</a>
        <?php endif; ?>
    </form>
</div>

<!-- 실적 테이블 -->
<div class="card">
    <div class="card-header">
        <h3>실적 목록 (<?= count($salesList) ?>건)</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><th style="">보고서</th><th>처리내역</th><th>등록일</th><th>관리</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($salesList as $_idx => $s):
                    $dupKey = $s['staff_id'].'-'.$s['company_name'].'-'.$s['episode'];
                    $isDup = isset($dupKeys[$dupKey]);
                ?>
                <tr>
                    <td><?= $_idx + 1 ?></td>
                    <td><strong><?= htmlspecialchars($s['staff_name']) ?></strong></td>
                    <td><span class="badge badge-info"><?= $s['grade'] ?></span></td>
                    <td><?= htmlspecialchars($s['team']) ?></td>
                    <td ><?= htmlspecialchars($s['company_name']) ?></td>
                    <td ><?= htmlspecialchars($s['program_name']) ?></td>
                    <td><?= htmlspecialchars($s['episode']) ?></td>
                    <td><?= $s['contract_date'] ?></td>
                    <td class="text-right font-mono"><?= number_format($s['revenue']) ?></td>
                    <td class="text-right font-mono"><?= number_format($s['cost']) ?></td>
                    <td class="text-right font-mono"><strong><?= number_format($s['net_profit']) ?></strong></td>
                    <td><?php $stg2=$s['stage']?:'미진행';?><span class="badge stage-<?=$stg2?>"><?=$stg2?></span></td>
                    <td><?= $s['confirm_type'] === '확정'
                        ? '<span class="badge badge-success">확정</span>'
                        : '<span class="badge badge-gray">예상</span>' ?></td>
                    <td style="font-size:var(--fs-xs);white-space:nowrap;"><?= $s['rpt_check_date'] ?? '-' ?></td>
                    <td style="font-size:var(--fs-xs);white-space:nowrap;"><?php $hn=$s['handler_name']??''; if($hn):?><span class="badge" style="background:rgba(88,166,255,0.15);color:#58a6ff;"><?=htmlspecialchars($hn)?></span><?php else:?>-<?php endif;?></td>
                    <td style="vertical-align:middle;"><?php if ($s['report_id']): ?>
                        <span onclick='openReportView(<?= json_encode(["report_id"=>$s["report_id"],"company"=>$s["rpt_company"]??'',"ceo"=>$s["rpt_ceo"]??'',"contact_name"=>$s["rpt_contact_name"]??'',"contact_phone"=>$s["rpt_contact_phone"]??'',"industry"=>$s["rpt_industry"]??'',"field"=>$s["rpt_field"]??'',"phone"=>$s["rpt_phone"]??'',"mobile"=>$s["rpt_mobile"]??'',"email"=>$s["rpt_email"]??'',"website"=>$s["rpt_website"]??'',"route"=>$s["rpt_route"]??'',"call_notes"=>$s["rpt_call_notes"]??'',"check_date"=>$s["rpt_check_date"]??'',"handler_name"=>$s["handler_name"]??'',"staff_name"=>$s["staff_name"]], JSON_UNESCAPED_UNICODE) ?>)' style="display:inline-block;background:var(--accent);color:#fff;font-size:0.75rem;font-weight:600;padding:0.25rem 0.65rem;border-radius:4px;cursor:pointer;line-height:1.4;white-space:nowrap;">📋 보기</span>
                    <?php else: ?><span style="display:inline-block;background:rgba(255,255,255,0.08);color:var(--text-tertiary);font-size:0.75rem;padding:0.25rem 0.65rem;border-radius:4px;line-height:1.4;white-space:nowrap;">없음</span><?php endif; ?></td>
                    <!-- 처리내역 -->
                    <td style="font-size:var(--fs-xs);white-space:nowrap;"><?php $cmts = $commentMap[$s['sale_id']] ?? []; if ($cmts): ?>
                        <span style="cursor:pointer;color:#FFD54F;font-weight:500;" onclick="openMgmt(<?= $s['sale_id'] ?>)">💬 <?= count($cmts) ?>건</span>
                    <?php else: ?>
                        <span style="cursor:pointer;color:#90A4AE;font-weight:500;" onclick="openMgmt(<?= $s['sale_id'] ?>)">💬 0</span>
                    <?php endif; ?>
                        <button onclick="openMgmt(<?= $s['sale_id'] ?>)" style="margin-left:0.35rem;background:var(--accent);color:var(--text-primary,#fff);border:none;border-radius:4px;font-size:0.68rem;font-weight:500;padding:0.2rem 0.5rem;cursor:pointer;vertical-align:middle;">처리내역입력</button>
                    </td>
                    <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= isset($s['created_at']) ? date('m/d', strtotime($s['created_at'])) : '-' ?></td>
                    <td style="white-space:nowrap;">
                        <?php
                        $isSysadmin = ($user['role'] === 'sysadmin');
                        $isCeo = ($user['role'] === 'ceo');
                        $isManager = ($user['role'] === 'manager');
                        $isAdmin = ($isSysadmin || $isCeo || $isManager);
                        $isOwner = ($s['staff_id'] == $user['staff_id']);
                        $canEdit = $isAdmin; // 시스템관리자/대표/관리자 직접 수정
                        $canDelete = $isAdmin; // 시스템관리자/대표/관리자 직접 삭제
                        $canRequestEdit = ($isOwner && !$isAdmin); // 본인 수정 요청 (일반 직원)
                        $canRequestDelete = ($isOwner && !$isAdmin); // 본인 삭제 요청 (일반 직원)
                        ?>
                        <?php if ($canEdit): ?>
                        <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;"
                            onclick='openEdit(<?= json_encode([
                                "sale_id"=>$s["sale_id"],"company_name"=>$s["company_name"],"program_name"=>$s["program_name"],
                                "episode"=>$s["episode"],"contract_date"=>$s["contract_date"],"filming_date"=>$s["filming_date"]??"",
                                "broadcast_date"=>$s["broadcast_date"]??"","revenue"=>$s["revenue"],"cost"=>$s["cost"],
                                "stage"=>$s["stage"],"confirm_type"=>$s["confirm_type"],"memo"=>$s["memo"]??"","handler_name"=>$s["handler_name"]??""
                            ],JSON_UNESCAPED_UNICODE) ?>)'>✏️</button>
                        <?php elseif ($canRequestEdit): ?>
                        <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;opacity:0.7;"
                            onclick='openEditRequest(<?= json_encode([
                                "sale_id"=>$s["sale_id"],"company_name"=>$s["company_name"],"program_name"=>$s["program_name"],
                                "episode"=>$s["episode"],"contract_date"=>$s["contract_date"],"filming_date"=>$s["filming_date"]??"",
                                "broadcast_date"=>$s["broadcast_date"]??"","revenue"=>$s["revenue"],"cost"=>$s["cost"],
                                "stage"=>$s["stage"],"confirm_type"=>$s["confirm_type"],"memo"=>$s["memo"]??"","handler_name"=>$s["handler_name"]??""
                            ],JSON_UNESCAPED_UNICODE) ?>)' title="수정 요청">✏️</button>
                        <?php endif; ?>
                        <?php if ($canDelete): ?>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('정말 삭제하시겠습니까?')">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="sale_id" value="<?= $s['sale_id'] ?>">
                            <button type="submit" class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;color:var(--accent);">🗑️</button>
                        </form>
                        <?php elseif ($canRequestDelete): ?>
                        <button class="btn btn-sm" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;color:var(--text-tertiary);"
                            onclick="openDeleteRequest(<?= $s['sale_id'] ?>)">🗑️</button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($salesList)): ?>
                <tr><td colspan="17" style="padding:2rem;color:var(--text-tertiary);">데이터가 존재하지 않습니다.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($totalCnt > 0): ?>
    <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 ($totalPages > 1): ?>
        <?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
        $startP = max(1, $page - 2);
        $endP = min($totalPages, $page + 2);
        for ($p = $startP; $p <= $endP; $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; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<div class="modal-overlay" id="addModal">
    <div class="modal" style="max-width:640px;">
        <div class="modal-header">
            <h3>💰 실적 등록</h3>
            <button class="modal-close" onclick="document.getElementById('addModal').classList.remove('show')">&times;</button>
        </div>
        <div style="display:flex;border-bottom:1px solid var(--border-color);margin-bottom:1rem;">
            <button type="button" class="sale-tab-btn active" onclick="switchSaleTab('info',this)" style="flex:1;padding:0.6rem;background:none;border:none;color:var(--text-primary);font-weight:700;cursor:pointer;border-bottom:2px solid var(--accent);font-size:var(--fs-sm);">📋 영업 정보</button>
            <button type="button" class="sale-tab-btn" onclick="switchSaleTab('report',this)" style="flex:1;padding:0.6rem;background:none;border:none;color:var(--text-tertiary);font-weight:500;cursor:pointer;border-bottom:2px solid transparent;font-size:var(--fs-sm);">📝 영업 보고서</button>
        </div>
        <form method="POST" action="<?=BASE_URL?>pages/sales.php">
            <input type="hidden" name="action" value="create">
            <input type="hidden" name="staff_id" value="<?= $user['staff_id'] ?>">
            <div id="saleTabInfo">
            <div class="form-row">
                <div class="form-group"><label>협찬 기업명 <span class="required">*</span></label><input type="text" name="company_name" id="add_company_name" required placeholder="예: LG생활건강" oninput="syncCompanyName(this.value)"></div>
                <div class="form-group"><label>프로그램명 <span class="required">*</span></label><input type="text" name="program_name" required placeholder="예: 편스토랑"></div>
                <div class="form-group"><label>회차</label><input type="text" name="episode" placeholder="예: 120회"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>계약일</label><input type="date" name="contract_date"></div>
                <div class="form-group"><label>촬영일</label><input type="date" name="filming_date"></div>
                <div class="form-group"><label>방송일</label><input type="date" name="broadcast_date"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>매출(협찬금) <span class="required">*</span></label><input type="number" name="revenue" min="0" required placeholder="0"></div>
                <div class="form-group"><label>비용(직접비/외주비)</label><input type="number" name="cost" min="0" value="0"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>진행 단계 <span class="required">*</span></label>
                    <select name="stage" required><option value="미진행">미진행</option><option value="리드">리드</option><option value="제안">제안</option><option value="계약" selected>계약</option><option value="촬영">촬영</option><option value="방송완료">방송완료</option></select></div>
                <div class="form-group"><label>확정/예상</label>
                    <select name="confirm_type"><option value="확정">확정</option><option value="예상">예상</option></select></div>
            </div>
            <div class="form-group"><label>비고</label><textarea name="memo" rows="2" placeholder="특이사항 입력"></textarea></div>
            </div>
            <div id="saleTabReport" style="display:none;">
                <div style="background:rgba(255,255,255,0.03);border:1px solid var(--border-color);border-radius:8px;padding:0.75rem;margin-bottom:0.75rem;">
                    <div style="font-size:var(--fs-xs);color:var(--text-tertiary);">📌 영업 보고서 작성 시 <strong style="color:var(--accent);">기업 DB에 자동 등록</strong>됩니다. 담당자: <strong style="color:var(--accent);"><?= htmlspecialchars($user['name']) ?></strong></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>업체명 <span class="required">*</span></label><input type="text" name="rpt_company_name" id="rpt_company_name" placeholder="업체명"></div>
                    <div class="form-group"><label>대표자명</label><input type="text" name="rpt_ceo_name" placeholder="대표자명"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>담당자명</label><input type="text" name="rpt_contact_name" placeholder="담당자명"></div>
                    <div class="form-group"><label>담당자 번호</label><input type="text" name="rpt_contact_phone" placeholder="010-0000-0000"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>업종</label><input type="text" name="rpt_industry" placeholder="예: 서비스업 / 개발업"></div>
                    <div class="form-group"><label>분야</label><input type="text" name="rpt_field" placeholder="예: 소프트웨어 개발"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>대표전화</label><input type="text" name="rpt_phone" placeholder="예: 02-1234-5678"></div>
                    <div class="form-group"><label>휴대폰</label><input type="text" name="rpt_mobile" placeholder="예: 010-1234-5678"></div>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>메일주소</label><input type="email" name="rpt_email" placeholder="예: info@company.com"></div>
                    <div class="form-group"><label>홈페이지</label><input type="url" name="rpt_website" placeholder="예: https://www.company.com"></div>
                </div>
                <div class="form-group"><label>컨택경로</label><input type="text" name="rpt_contact_route" placeholder="예: 지인 소개, 전화 영업, SNS 등"></div>
                <div class="form-row">
                    <div class="form-group"><label>진행 확인일</label><input type="date" name="rpt_check_date"></div>
                </div>
                <div class="form-group"><label>통화 내용</label><textarea name="rpt_call_notes" rows="4" placeholder="통화 내용을 입력하세요" style="resize:vertical;"></textarea></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('addModal').classList.remove('show')">취소</button>
            </div>
        </form>
    </div>
</div>
<script>
function switchSaleTab(tab, btn) {
    document.getElementById('saleTabInfo').style.display = tab==='info'?'':'none';
    document.getElementById('saleTabReport').style.display = tab==='report'?'':'none';
    document.querySelectorAll('.sale-tab-btn').forEach(function(b){
        b.style.color='var(--text-tertiary)';b.style.fontWeight='500';b.style.borderBottom='2px solid transparent';
    });
    btn.style.color='var(--text-primary)';btn.style.fontWeight='700';btn.style.borderBottom='2px solid var(--accent)';
}
function syncCompanyName(val) {
    var rpt = document.getElementById('rpt_company_name');
    if (rpt && (!rpt.value || rpt.dataset.synced !== 'false')) { rpt.value = val; rpt.dataset.synced = 'true'; }
}
document.addEventListener('DOMContentLoaded', function() {
    var rpt = document.getElementById('rpt_company_name');
    if (rpt) rpt.addEventListener('input', function() { this.dataset.synced = 'false'; });
});
</script>

<!-- 영업 보고서 보기 모달 -->
<div class="modal-overlay" id="reportViewModal">
    <div class="modal" style="max-width:560px;">
        <div class="modal-header">
            <h3>📝 영업 보고서</h3>
            <button class="modal-close" onclick="document.getElementById('reportViewModal').classList.remove('show')">&times;</button>
        </div>
        <div id="rvBody" style="font-size:var(--fs-sm);text-align:left;">
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">업체명</span><span style="font-weight:600;" id="rv_company"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">대표자명</span><span id="rv_ceo"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">담당자명</span><span id="rv_contact_name"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">담당자번호</span><span id="rv_contact_phone"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">업종</span><span id="rv_industry"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">분야</span><span id="rv_field"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">대표전화</span><span id="rv_phone"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">휴대폰</span><span id="rv_mobile"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">메일주소</span><span id="rv_email"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">홈페이지</span><span id="rv_website"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">컨택경로</span><span id="rv_route"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">진행확인일</span><span id="rv_check_date"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">처리자</span><span id="rv_handler"></span></div>
            <div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">통화내용</span><span style="white-space:pre-wrap;" id="rv_call_notes"></span></div>
            <div style="padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);">
                <div style="display:flex;align-items:flex-start;"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);padding-top:0.2rem;">녹음파일</span><div id="rv_audio_wrap" style="flex:1;"></div></div>
            </div>
            <div style="display:flex;padding:0.4rem 0;"><span style="width:90px;flex-shrink:0;color:var(--text-tertiary);">담당자</span><span style="color:var(--accent);font-weight:600;" id="rv_staff"></span></div>
        </div>
        <div class="btn-group mt-16" style="text-align:center;justify-content:center;">
            <button type="button" class="btn btn-outline" style="font-size:var(--fs-xs);" onclick="openReportEditReq()">✏️ 수정 요청</button>
            <button type="button" class="btn btn-outline" onclick="document.getElementById('reportViewModal').classList.remove('show')">닫기</button>
        </div>
    </div>
</div>

<!-- 영업 보고서 수정 요청 모달 -->
<div class="modal-overlay" id="reportEditReqModal">
    <div class="modal" style="max-width:560px;">
        <div class="modal-header">
            <h3>✏️ 보고서 수정 요청</h3>
            <button class="modal-close" onclick="document.getElementById('reportEditReqModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="request_report_edit">
            <input type="hidden" name="report_id" id="rre_id">
            <div class="form-row">
                <div class="form-group"><label>업체명</label><input type="text" name="rpt_company_name" id="rre_company"></div>
                <div class="form-group"><label>대표자명</label><input type="text" name="rpt_ceo_name" id="rre_ceo"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>담당자명</label><input type="text" name="rpt_contact_name" id="rre_contact_name"></div>
                <div class="form-group"><label>담당자 번호</label><input type="text" name="rpt_contact_phone" id="rre_contact_phone"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>업종</label><input type="text" name="rpt_industry" id="rre_industry"></div>
                <div class="form-group"><label>분야</label><input type="text" name="rpt_field" id="rre_field"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>대표전화</label><input type="text" name="rpt_phone" id="rre_phone"></div>
                <div class="form-group"><label>휴대폰</label><input type="text" name="rpt_mobile" id="rre_mobile"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>메일주소</label><input type="email" name="rpt_email" id="rre_email"></div>
                <div class="form-group"><label>홈페이지</label><input type="url" name="rpt_website" id="rre_website"></div>
            </div>
            <div class="form-group"><label>컨택경로</label><input type="text" name="rpt_contact_route" id="rre_route"></div>
            <div class="form-row">
                <div class="form-group"><label>진행 확인일</label><input type="date" name="rpt_check_date" id="rre_check_date"></div>
            </div>
            <div class="form-group"><label>통화내용</label><textarea name="rpt_call_notes" id="rre_call_notes" rows="3"></textarea></div>
            <div class="form-group">
                <label>수정 사유 <span class="required">*</span></label>
                <textarea name="reason" rows="2" 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('reportEditReqModal').classList.remove('show')">취소</button>
            </div>
        </form>
    </div>
</div>

<script>
var _currentReport = {};
var _callFilesByReport = <?= json_encode($callFileMapByReport, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>;
function openReportView(d) {
    _currentReport = d;
    document.getElementById('rv_company').textContent = d.company||'-';
    document.getElementById('rv_ceo').textContent = d.ceo||'-';
    document.getElementById('rv_contact_name').textContent = d.contact_name||'-';
    document.getElementById('rv_contact_phone').textContent = d.contact_phone||'-';
    document.getElementById('rv_industry').textContent = d.industry||'-';
    document.getElementById('rv_field').textContent = d.field||'-';
    document.getElementById('rv_phone').textContent = d.phone||'-';
    document.getElementById('rv_mobile').textContent = d.mobile||'-';
    document.getElementById('rv_email').textContent = d.email||'-';
    document.getElementById('rv_website').textContent = d.website||'-';
    document.getElementById('rv_route').textContent = d.route||'-';
    document.getElementById('rv_check_date').textContent = d.check_date||'-';
    document.getElementById('rv_handler').textContent = d.handler_name||'-';
    document.getElementById('rv_call_notes').textContent = d.call_notes||'-';
    document.getElementById('rv_staff').textContent = d.staff_name||'-';
    /* 녹음 파일 */
    var aw = document.getElementById('rv_audio_wrap');
    var files = _callFilesByReport[d.report_id] || [];
    var baseUrl = '<?=BASE_URL?>';
    if (!files.length) {
        aw.innerHTML = '<span style="color:var(--text-tertiary);font-size:14px;">없음</span>';
    } else {
        var h = '';
        files.forEach(function(cf) {
            var dt = cf.created_at ? cf.created_at.substring(0,10) : '';
            h += '<div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.3rem;padding:0.3rem 0.5rem;background:rgba(255,255,255,0.03);border-radius:6px;">';
            h += '<span style="font-size:14px;color:var(--text-tertiary);white-space:nowrap;min-width:75px;">'+dt+'</span>';
            h += '<audio controls preload="metadata" style="height:2rem;flex:1;min-width:0;"><source src="'+baseUrl+cf.file_path+'"></audio>';
            h += '<a href="'+baseUrl+cf.file_path+'" download style="font-size:14px;color:var(--accent);white-space:nowrap;">📥</a>';
            h += '</div>';
        });
        aw.innerHTML = h;
    }
    document.getElementById('reportViewModal').classList.add('show');
}
function openReportEditReq() {
    var d = _currentReport;
    document.getElementById('rre_id').value = d.report_id||'';
    document.getElementById('rre_company').value = d.company||'';
    document.getElementById('rre_ceo').value = d.ceo||'';
    document.getElementById('rre_contact_name').value = d.contact_name||'';
    document.getElementById('rre_contact_phone').value = d.contact_phone||'';
    document.getElementById('rre_industry').value = d.industry||'';
    document.getElementById('rre_field').value = d.field||'';
    document.getElementById('rre_phone').value = d.phone||'';
    document.getElementById('rre_mobile').value = d.mobile||'';
    document.getElementById('rre_email').value = d.email||'';
    document.getElementById('rre_website').value = d.website||'';
    document.getElementById('rre_route').value = d.route||'';
    document.getElementById('rre_check_date').value = d.check_date||'';
    document.getElementById('rre_call_notes').value = d.call_notes||'';
    document.getElementById('reportViewModal').classList.remove('show');
    document.getElementById('reportEditReqModal').classList.add('show');
}
</script>

<!-- 수정 모달 -->
<div class="modal-overlay" id="editModal">
    <div class="modal">
        <div class="modal-header">
            <h3>✏️ 검토 내역 작성</h3>
            <button class="modal-close" onclick="document.getElementById('editModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST" action="<?=BASE_URL?>pages/sales.php">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="sale_id" id="e_sale_id">
            <div class="form-row">
                <div class="form-group"><label>협찬 기업명 <span class="required">*</span></label><input type="text" name="company_name" id="e_company" required></div>
                <div class="form-group"><label>프로그램명 <span class="required">*</span></label><input type="text" name="program_name" id="e_program" required></div>
                <div class="form-group"><label>회차</label><input type="text" name="episode" id="e_episode"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>계약일</label><input type="date" name="contract_date" id="e_cdate"></div>
                <div class="form-group"><label>촬영일</label><input type="date" name="filming_date" id="e_fdate"></div>
                <div class="form-group"><label>방송일</label><input type="date" name="broadcast_date" id="e_bdate"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>매출(협찬금)</label><input type="number" name="revenue" id="e_rev"></div>
                <div class="form-group"><label>비용(직접비/외주비)</label><input type="number" name="cost" id="e_cost"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>진행 단계</label>
                    <select name="stage" id="e_stage"><option>미진행</option><option>계약</option><option>촬영</option><option>방송완료</option><option>리드</option><option>제안</option></select></div>
                <div class="form-group"><label>확정/예상</label>
                    <select name="confirm_type" id="e_confirm"><option>확정</option><option>예상</option></select></div>
            </div>
            <div class="form-group"><label>처리자</label><select name="handler_name" id="e_handler"><option value="">선택</option><?php foreach($handlerList as $hl):?><option value="<?=htmlspecialchars($hl['name'])?>"><?=htmlspecialchars($hl['name'])?></option><?php endforeach;?></select></div>
            <div class="form-group"><label>비고</label><textarea name="memo" id="e_memo" rows="2"></textarea></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('editModal').classList.remove('show')">취소</button>
            </div>
        </form>
    </div>
</div>
<script>
function openEdit(d) {
    document.getElementById('e_sale_id').value = d.sale_id;
    document.getElementById('e_company').value = d.company_name;
    document.getElementById('e_program').value = d.program_name;
    document.getElementById('e_episode').value = d.episode;
    document.getElementById('e_cdate').value = d.contract_date||'';
    document.getElementById('e_fdate').value = d.filming_date||'';
    document.getElementById('e_bdate').value = d.broadcast_date||'';
    document.getElementById('e_rev').value = parseInt(d.revenue||0).toLocaleString();
    document.getElementById('e_cost').value = parseInt(d.cost||0).toLocaleString();
    document.getElementById('e_stage').value = d.stage;
    document.getElementById('e_confirm').value = d.confirm_type;
    document.getElementById('e_memo').value = d.memo||'';
    document.getElementById('e_handler').value = d.handler_name||'';
    document.getElementById('editModal').classList.add('show');
}
</script>

<!-- 수정 요청 모달 -->
<div class="modal-overlay" id="editReqModal">
    <div class="modal">
        <div class="modal-header">
            <h3>✏️ 검토 내역 작성 요청</h3>
            <button class="modal-close" onclick="document.getElementById('editReqModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="request_edit">
            <input type="hidden" name="sale_id" id="er_sale_id">
            <div class="form-row">
                <div class="form-group"><label>협찬 기업명</label><input type="text" name="company_name" id="er_company" required></div>
                <div class="form-group"><label>프로그램명</label><input type="text" name="program_name" id="er_program" required></div>
                <div class="form-group"><label>회차</label><input type="text" name="episode" id="er_episode"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>계약일</label><input type="date" name="contract_date" id="er_cdate"></div>
                <div class="form-group"><label>촬영일</label><input type="date" name="filming_date" id="er_fdate"></div>
                <div class="form-group"><label>방송일</label><input type="date" name="broadcast_date" id="er_bdate"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>매출</label><input type="number" name="revenue" id="er_rev"></div>
                <div class="form-group"><label>비용</label><input type="number" name="cost" id="er_cost"></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>단계</label><select name="stage" id="er_stage"><option>미진행</option><option>리드</option><option>제안</option><option>계약</option><option>촬영</option><option>방송완료</option></select></div>
                <div class="form-group"><label>확정/예상</label><select name="confirm_type" id="er_confirm"><option>확정</option><option>예상</option></select></div>
            </div>
            <div class="form-group"><label>비고</label><textarea name="memo" id="er_memo" rows="2"></textarea></div>
            <div class="form-group"><label>수정 사유</label><input type="text" name="edit_reason" placeholder="수정 사유를 입력하세요"></div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);">시스템 관리자 승인 후 수정 반영됩니다.</div>
            <button type="submit" class="btn btn-primary">수정 요청</button>
        </form>
    </div>
</div>

<!-- 삭제 요청 모달 -->
<div class="modal-overlay" id="delReqModal">
    <div class="modal" style="max-width:400px;">
        <div class="modal-header">
            <h3>🗑️ 삭제 요청</h3>
            <button class="modal-close" onclick="document.getElementById('delReqModal').classList.remove('show')">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="request_delete">
            <input type="hidden" name="sale_id" id="dr_sale_id">
            <div class="form-group">
                <label>삭제 사유</label>
                <textarea name="reason" rows="2" placeholder="삭제 사유를 입력하세요"></textarea>
            </div>
            <div class="alert alert-info" style="font-size:var(--fs-xs);">시스템 관리자 승인 후 삭제됩니다.</div>
            <button type="submit" class="btn btn-primary">요청</button>
        </form>
    </div>
</div>

<?php
// 수정/삭제 요청 목록 (sysadmin, ceo, manager)
if (in_array($user['role'], ['sysadmin','ceo','manager'])) {
    $db->exec("CREATE TABLE IF NOT EXISTS delete_request (req_id INT AUTO_INCREMENT PRIMARY KEY, sale_id INT NOT NULL, requested_by INT NOT NULL, reason VARCHAR(200) DEFAULT '', status ENUM('대기','승인','거절') DEFAULT '대기', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, resolved_at DATETIME DEFAULT NULL)");
    $db->exec("CREATE TABLE IF NOT EXISTS edit_request (req_id INT AUTO_INCREMENT PRIMARY KEY, sale_id INT NOT NULL, requested_by INT NOT NULL, edit_data TEXT, reason VARCHAR(200) DEFAULT '', status ENUM('대기','승인','거절') DEFAULT '대기', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, resolved_at DATETIME DEFAULT NULL)");
    $pendingEdit = $db->query("SELECT er.*, s.company_name AS orig_company, s.program_name AS orig_program, st.name AS requester_name FROM edit_request er LEFT JOIN sales s ON er.sale_id=s.sale_id LEFT JOIN staff st ON er.requested_by=st.staff_id WHERE er.status='대기' ORDER BY er.created_at DESC")->fetchAll();
    if ($pendingEdit):
?>
<div class="card" style="margin-top:1.25rem;">
    <div class="card-header"><h3>✏️ 수정 요청 대기 (<?= count($pendingEdit) ?>건)</h3></div>
    <table class="data-table">
        <thead><tr><th>요청자</th><th>기업명</th><th>프로그램</th><th>사유</th><th>요청일</th><th>처리</th></tr></thead>
        <tbody>
        <?php foreach ($pendingEdit as $pe):
            $ed = json_decode($pe['edit_data'], true);
        ?>
        <tr>
            <td><strong><?= htmlspecialchars($pe['requester_name']??'-') ?></strong></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($pe['orig_company']??'') ?> → <strong><?= htmlspecialchars($ed['company_name']??'') ?></strong></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($pe['orig_program']??'') ?> → <strong><?= htmlspecialchars($ed['program_name']??'') ?></strong></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($pe['reason']??'-') ?></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= date('m/d H:i', strtotime($pe['created_at'])) ?></td>
            <td style="white-space:nowrap;">
                <form method="POST" style="display:inline;"><input type="hidden" name="action" value="approve_edit"><input type="hidden" name="req_id" value="<?= $pe['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_edit"><input type="hidden" name="req_id" value="<?= $pe['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>
<?php endif;
    $pendingDel = $db->query("SELECT dr.*, s.company_name, s.program_name, st.name AS requester_name FROM delete_request dr LEFT JOIN sales s ON dr.sale_id=s.sale_id LEFT JOIN staff st ON dr.requested_by=st.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>
    <table class="data-table">
        <thead><tr><th>요청자</th><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><?= htmlspecialchars($pd['program_name']??'-') ?></td>
            <td style="font-size:var(--fs-xs);"><?= 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>
<?php endif; } ?>

<!-- 관리(처리내역) 모달 -->
<div class="modal-overlay" id="mgmtModal">
    <div class="modal" style="max-width:560px;">
        <div class="modal-header"><h3>📋 관리 - 처리내역</h3><button class="modal-close" onclick="document.getElementById('mgmtModal').classList.remove('show')">&times;</button></div>
        <div id="mgmtSaleInfo" style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.75rem;"></div>
        <div id="mgmtComments" style="max-height:300px;overflow-y:auto;margin-bottom:0.75rem;"></div>
        <form method="POST" style="display:flex;gap:0.5rem;align-items:flex-end;">
            <input type="hidden" name="action" value="add_comment">
            <input type="hidden" name="sale_id" id="mgmt_sale_id">
            <div style="flex:1;"><textarea name="content" id="mgmt_textarea" rows="1" required placeholder="처리내역 입력..." style="resize:none;overflow:hidden;width:100%;min-height:2.2rem;line-height:1.5;"></textarea></div>
            <button type="submit" class="btn btn-primary" style="padding:0.4rem 0.8rem;font-size:var(--fs-xs);white-space:nowrap;">등록</button>
        </form>
    </div>
</div>
<script>
var _allComments = <?= json_encode($commentMap, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>;
var _userStaffId = <?= $user['staff_id'] ?>;
var _isAdminRole = <?= in_array($user['role'],['sysadmin','ceo','manager'])?'true':'false' ?>;

/* ── textarea 자동 높이 조절 (input, paste, 초기값 모두 대응) ── */
function autoResize(el) {
    el.style.height = 'auto';
    el.style.height = Math.max(el.scrollHeight, 34) + 'px';
}
(function() {
    var ta = document.getElementById('mgmt_textarea');
    if (!ta) return;
    ['input','paste','change','keydown'].forEach(function(evt) {
        ta.addEventListener(evt, function() {
            var self = this;
            setTimeout(function(){ autoResize(self); }, 0);
        });
    });
})();

function openMgmt(saleId) {
    document.getElementById('mgmt_sale_id').value = saleId;
    var ta = document.getElementById('mgmt_textarea');
    if (ta) { ta.value = ''; ta.style.height = 'auto'; }
    /* 처리내역 */
    var cmts = _allComments[saleId] || [];
    var h = '';
    if (!cmts.length) h = '<div style="color:var(--text-tertiary);font-size:var(--fs-sm);padding:0.5rem;">처리내역이 없습니다.</div>';
    else cmts.forEach(function(c) {
        var canEdit = (c.staff_id == _userStaffId || _isAdminRole);
        h += '<div id="cmt_wrap_'+c.comment_id+'" style="padding:0.5rem;margin-bottom:0.4rem;background:rgba(255,255,255,0.03);border-radius:6px;border-left:3px solid var(--accent);">';
        h += '<div style="display:flex;justify-content:space-between;align-items:center;"><span style="font-size:var(--fs-xs);color:var(--accent);font-weight:600;">'+c.author_name+'</span>';
        if (canEdit) h += '<span style="display:flex;gap:0.25rem;align-items:center;"><button onclick="editCmtInline('+c.comment_id+')" style="background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:14px;">✏️</button><form method="POST" style="display:inline;" onsubmit="return confirm(\'삭제?\')"><input type="hidden" name="action" value="delete_comment"><input type="hidden" name="comment_id" value="'+c.comment_id+'"><button type="submit" style="background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:14px;">🗑️</button></form></span>';
        h += '</div>';
        h += '<div id="cmt_view_'+c.comment_id+'" style="font-size:var(--fs-sm);white-space:pre-wrap;margin:0.25rem 0;">'+c.content+'</div>';
        h += '<div id="cmt_edit_'+c.comment_id+'" style="display:none;margin:0.25rem 0;">';
        h += '<textarea id="cmt_ta_'+c.comment_id+'" style="width:100%;resize:none;overflow:hidden;min-height:2.2rem;line-height:1.5;font-size:var(--fs-sm);border-radius:4px;padding:0.3rem 0.5rem;" rows="1">'+c.content.replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</textarea>';
        h += '<div style="display:flex;gap:0.3rem;margin-top:0.3rem;justify-content:flex-end;">';
        h += '<button onclick="saveCmtInline('+c.comment_id+')" style="background:var(--accent);color:#fff;border:none;border-radius:4px;font-size:14px;padding:0.3rem 0.75rem;cursor:pointer;">저장</button>';
        h += '<button onclick="cancelCmtInline('+c.comment_id+')" style="background:rgba(255,255,255,0.08);color:var(--text-secondary);border:none;border-radius:4px;font-size:14px;padding:0.3rem 0.75rem;cursor:pointer;">취소</button>';
        h += '</div></div>';
        h += '<div style="font-size:0.65rem;color:var(--text-tertiary);">'+c.created_at+'</div></div>';
    });
    document.getElementById('mgmtComments').innerHTML = h;
    document.getElementById('mgmtModal').classList.add('show');
    /* 수정 textarea에도 자동 높이 바인딩 */
    cmts.forEach(function(c) {
        var eta = document.getElementById('cmt_ta_'+c.comment_id);
        if (eta) {
            ['input','paste','change','keydown'].forEach(function(evt) {
                eta.addEventListener(evt, function() { var self = this; setTimeout(function(){ autoResize(self); }, 0); });
            });
        }
    });
}

function editCmtInline(cid) {
    document.getElementById('cmt_view_'+cid).style.display = 'none';
    var editDiv = document.getElementById('cmt_edit_'+cid);
    editDiv.style.display = 'block';
    var ta = document.getElementById('cmt_ta_'+cid);
    if (ta) { autoResize(ta); ta.focus(); }
}
function cancelCmtInline(cid) {
    document.getElementById('cmt_view_'+cid).style.display = '';
    document.getElementById('cmt_edit_'+cid).style.display = 'none';
}
function saveCmtInline(cid) {
    var ta = document.getElementById('cmt_ta_'+cid);
    var nc = ta ? ta.value.trim() : '';
    if (!nc) { alert('내용을 입력해주세요.'); return; }
    var f = document.createElement('form'); f.method='POST'; f.style.display='none';
    f.innerHTML = '<input name="action" value="update_comment"><input name="comment_id" value="'+cid+'"><textarea name="content" style="display:none;">'+nc.replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</textarea>';
    document.body.appendChild(f); f.submit();
}
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
