<?php
// pages/sales_report.php — 실적 보고서 관리
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
$db = (new Database())->getConnection();
// 빈 stage를 미진행으로 자동 업데이트
try { $db->exec("UPDATE sales SET stage='미진행' WHERE stage IS NULL OR stage=''"); } catch(Exception $e) {}
$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 '',contact_name VARCHAR(50) DEFAULT '' COMMENT '담당자명',contact_phone VARCHAR(30) DEFAULT '' COMMENT '담당자번호',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,check_date DATE DEFAULT NULL COMMENT '진행확인일',handler_name VARCHAR(50) DEFAULT '' 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");
// check_date 컬럼 없으면 추가
try{$db->query("SELECT check_date FROM sales_report LIMIT 0");}catch(Exception $e){try{$db->exec("ALTER TABLE sales_report ADD COLUMN check_date DATE DEFAULT NULL COMMENT '진행확인일' AFTER call_notes");}catch(Exception $e2){}}
// handler_name 컬럼 없으면 추가
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 '처리자' AFTER check_date");}catch(Exception $e2){}}
// 기존 progress_method 컬럼 제거 (진행방법 → 처리자로 대체됨)
try{$db->query("SELECT progress_method FROM sales_report LIMIT 0");$db->exec("ALTER TABLE sales_report DROP COLUMN progress_method");}catch(Exception $e){}
try{$db->query("SELECT progress_method FROM sales LIMIT 0");$db->exec("ALTER TABLE sales DROP COLUMN progress_method");}catch(Exception $e){}
// contact_name, contact_phone 컬럼 없으면 추가
try{$db->query("SELECT contact_name FROM sales_report LIMIT 0");}catch(Exception $e){try{$db->exec("ALTER TABLE sales_report ADD COLUMN contact_name VARCHAR(50) DEFAULT '' COMMENT '담당자명' AFTER ceo_name, ADD COLUMN contact_phone VARCHAR(30) DEFAULT '' COMMENT '담당자번호' AFTER contact_name");}catch(Exception $e2){}}
$db->exec("CREATE TABLE IF NOT EXISTS report_call_files (file_id INT AUTO_INCREMENT PRIMARY KEY,report_id INT NOT NULL,staff_id INT NOT NULL,file_path VARCHAR(300) NOT NULL,original_name VARCHAR(200) DEFAULT '',file_size INT DEFAULT 0,created_at DATETIME DEFAULT CURRENT_TIMESTAMP,INDEX idx_report(report_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
// 기존 call_file 컬럼 데이터 → report_call_files 마이그레이션 (1회성)
try{$db->query("SELECT call_file FROM sales_report LIMIT 0");
    $migRows=$db->query("SELECT report_id,staff_id,call_file,created_at FROM sales_report WHERE call_file IS NOT NULL AND call_file!=''")->fetchAll();
    if($migRows){foreach($migRows as $mr){$chk=$db->prepare("SELECT COUNT(*) FROM report_call_files WHERE report_id=? AND file_path=?");$chk->execute([$mr['report_id'],$mr['call_file']]);
        if(!$chk->fetchColumn()){$db->prepare("INSERT INTO report_call_files (report_id,staff_id,file_path,original_name,file_size,created_at) VALUES(?,?,?,?,0,?)")->execute([$mr['report_id'],$mr['staff_id'],$mr['call_file'],basename($mr['call_file']),$mr['created_at']]);}}
    }
}catch(Exception $e){}
$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 '',contact_name VARCHAR(50) DEFAULT '' COMMENT '담당자명',contact_phone VARCHAR(30) DEFAULT '' COMMENT '담당자번호',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");
try{$db->query("SELECT contact_name FROM company_db LIMIT 0");}catch(Exception $e){try{$db->exec("ALTER TABLE company_db ADD COLUMN contact_name VARCHAR(50) DEFAULT '' COMMENT '담당자명' AFTER ceo_name, ADD COLUMN contact_phone VARCHAR(30) DEFAULT '' COMMENT '담당자번호' AFTER contact_name");}catch(Exception $e2){}}
$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->exec("CREATE TABLE IF NOT EXISTS report_delete_request (req_id INT AUTO_INCREMENT PRIMARY KEY,report_id INT NOT NULL,requested_by INT NOT NULL,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->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");

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action'])) {
    session_start();
    if (!isset($_SESSION['user_id'])) { header("Location: ".BASE_URL."index.php"); exit; }
    $ur=$_SESSION['user_role']??'staff'; $uid=$_SESSION['staff_id']??0; $uname=$_SESSION['name']??'';
    $adm=in_array($ur,['ceo','sysadmin','manager']); $msg='';

    if ($_POST['action']==='create_report') {
        $cn=trim($_POST['company_name']??'');
        if ($cn) { try {
            $db->prepare("INSERT INTO sales_report (staff_id,company_name,ceo_name,contact_name,contact_phone,industry,field,phone,mobile,email,website,contact_route,call_notes,check_date) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
               ->execute([$uid,$cn,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']??''),trim($_POST['call_notes']??''),($_POST['check_date']??'')?:null]);
            $rid=$db->lastInsertId(); writeAudit($db,'sales_report',$rid,'INSERT',['company'=>$cn]);
            // 통화 녹음 파일(들) 업로드
            if (!empty($_FILES['call_files']['name'][0])) {
                $uploadDir = __DIR__ . '/../uploads/call_records/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                $allowed = ['mp3','wav','ogg','m4a','aac','wma','flac','webm','mp4','3gp','amr'];
                $insF = $db->prepare("INSERT INTO report_call_files (report_id,staff_id,file_path,original_name,file_size) VALUES(?,?,?,?,?)");
                foreach ($_FILES['call_files']['name'] as $fi => $fname_orig) {
                    if ($_FILES['call_files']['error'][$fi] !== UPLOAD_ERR_OK) continue;
                    $ext = strtolower(pathinfo($fname_orig, PATHINFO_EXTENSION));
                    $fsize = $_FILES['call_files']['size'][$fi];
                    if (!in_array($ext, $allowed) || $fsize > 50*1024*1024) continue;
                    $fname = date('Ymd_His').'_'.$uid.'_'.bin2hex(random_bytes(4)).'.'.$ext;
                    if (move_uploaded_file($_FILES['call_files']['tmp_name'][$fi], $uploadDir.$fname)) {
                        $insF->execute([$rid, $uid, 'uploads/call_records/'.$fname, $fname_orig, $fsize]);
                    }
                }
            }
            $stageVal = $_POST['stage'] ?? '미진행';
            if (!in_array($stageVal, ['미진행','리드','제안','계약','촬영','방송완료'])) $stageVal = '미진행';
            $db->prepare("INSERT INTO sales (staff_id,company_name,program_name,episode,revenue,cost,net_profit,stage,confirm_type,memo,sale_month) VALUES(?,?,'','',0,0,0,?,'예상','',NULL)")->execute([$uid,$cn,$stageVal]);
            $sid=$db->lastInsertId(); $db->prepare("UPDATE sales_report SET sale_id=? WHERE report_id=?")->execute([$sid,$rid]);
            $dup=$db->prepare("SELECT company_id FROM company_db WHERE company_name=? AND is_active=1"); $dup->execute([$cn]); $ec=$dup->fetchColumn();
            if (!$ec) { $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([$cn,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']??''),$uid,'영업보고서',$rid]);
            } else { $db->prepare("UPDATE company_db SET ceo_name=COALESCE(NULLIF(?,''),ceo_name),contact_name=COALESCE(NULLIF(?,''),contact_name),contact_phone=COALESCE(NULLIF(?,''),contact_phone),industry=COALESCE(NULLIF(?,''),industry),field=COALESCE(NULLIF(?,''),field),phone=COALESCE(NULLIF(?,''),phone),mobile=COALESCE(NULLIF(?,''),mobile),email=COALESCE(NULLIF(?,''),email),website=COALESCE(NULLIF(?,''),website),contact_route=COALESCE(NULLIF(?,''),contact_route) WHERE company_id=?")
               ->execute([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']??''),$ec]); }
            $msg='보고서가 등록되었습니다.';
        } catch(PDOException $e){$msg='오류: '.$e->getMessage();} } else {$msg='업체명 필수';}
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    if ($_POST['action']==='request_edit') {
        $rid=(int)($_POST['report_id']??0); $reason=trim($_POST['reason']??'');
        if ($rid && $reason) {
            $ed=json_encode(['company_name'=>trim($_POST['company_name']??''),'ceo_name'=>trim($_POST['ceo_name']??''),'contact_name'=>trim($_POST['contact_name']??''),'contact_phone'=>trim($_POST['contact_phone']??''),'industry'=>trim($_POST['industry']??''),'field'=>trim($_POST['field']??''),'phone'=>trim($_POST['phone']??''),'mobile'=>trim($_POST['mobile']??''),'email'=>trim($_POST['email']??''),'website'=>trim($_POST['website']??''),'contact_route'=>trim($_POST['contact_route']??''),'call_notes'=>trim($_POST['call_notes']??''),'check_date'=>($_POST['check_date']??'')?:null,'stage'=>trim($_POST['stage']??'미진행')],JSON_UNESCAPED_UNICODE);
            $db->prepare("INSERT INTO report_edit_request (report_id,requested_by,edit_data,reason) VALUES(?,?,?,?)")->execute([$rid,$uid,$ed,$reason]);
            try{$aa=$db->query("SELECT user_id FROM user_account WHERE user_role IN('sysadmin','ceo','manager') AND is_active=1")->fetchAll(PDO::FETCH_COLUMN);foreach($aa as $a)$db->prepare("INSERT INTO notifications (user_id,message,link) VALUES(?,?,?)")->execute([$a,"📝 {$uname}님이 보고서 수정 요청",BASE_URL.'pages/sales_report.php']);}catch(Exception $e){}
            $msg='수정 요청 접수';
        } else {$msg='사유를 입력하세요.';}
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    if ($_POST['action']==='approve_edit' && $adm) {
        $qid=(int)($_POST['req_id']??0); $dec=$_POST['decision']??'';
        if ($qid && in_array($dec,['승인','거절'])) {
            $db->prepare("UPDATE report_edit_request SET status=?,reviewed_by=?,resolved_at=NOW() WHERE req_id=?")->execute([$dec,$uid,$qid]);
            if ($dec==='승인') {
                $rq=$db->prepare("SELECT * FROM report_edit_request WHERE req_id=?"); $rq->execute([$qid]); $req=$rq->fetch();
                if ($req) { $ed=json_decode($req['edit_data'],true);
                    $old=$db->prepare("SELECT company_name,sale_id FROM sales_report WHERE report_id=?"); $old->execute([$req['report_id']]); $or=$old->fetch();
                    $db->prepare("UPDATE sales_report SET company_name=?,ceo_name=?,contact_name=?,contact_phone=?,industry=?,field=?,phone=?,mobile=?,email=?,website=?,contact_route=?,call_notes=?,check_date=? WHERE report_id=?")->execute([$ed['company_name']??'',$ed['ceo_name']??'',$ed['contact_name']??'',$ed['contact_phone']??'',$ed['industry']??'',$ed['field']??'',$ed['phone']??'',$ed['mobile']??'',$ed['email']??'',$ed['website']??'',$ed['contact_route']??'',$ed['call_notes']??'',($ed['check_date']??'')?:null,$req['report_id']]);
                    if($or&&$or['sale_id']){$db->prepare("UPDATE sales SET company_name=?,stage=? WHERE sale_id=?")->execute([$ed['company_name']??'',$ed['stage']??'미진행',$or['sale_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 source_report_id=?")->execute([$ed['company_name']??'',$ed['ceo_name']??'',$ed['contact_name']??'',$ed['contact_phone']??'',$ed['industry']??'',$ed['field']??'',$ed['phone']??'',$ed['mobile']??'',$ed['email']??'',$ed['website']??'',$ed['contact_route']??'',$req['report_id']]);}catch(Exception $e){}
                    if($or&&$or['company_name']&&$or['company_name']!==($ed['company_name']??'')){try{$db->prepare("UPDATE company_db SET company_name=? WHERE company_name=? AND is_active=1")->execute([$ed['company_name'],$or['company_name']]);}catch(Exception $e){}}
                } $msg='수정 승인 완료';
            } else {$msg='수정 거절';}
        } header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    if ($_POST['action']==='request_delete') {
        $rid=(int)($_POST['report_id']??0); $reason=trim($_POST['reason']??'');
        if ($rid && $reason) {
            $db->prepare("INSERT INTO report_delete_request (report_id,requested_by,reason) VALUES(?,?,?)")->execute([$rid,$uid,$reason]);
            try{$aa=$db->query("SELECT user_id FROM user_account WHERE user_role IN('sysadmin','ceo','manager') AND is_active=1")->fetchAll(PDO::FETCH_COLUMN);foreach($aa as $a)$db->prepare("INSERT INTO notifications (user_id,message,link) VALUES(?,?,?)")->execute([$a,"🗑️ {$uname}님이 보고서 삭제 요청",BASE_URL.'pages/sales_report.php']);}catch(Exception $e){}
            $msg='삭제 요청 접수';
        } else {$msg='사유를 입력하세요.';}
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    if ($_POST['action']==='approve_delete' && $adm) {
        $qid=(int)($_POST['req_id']??0); $dec=$_POST['decision']??'';
        if ($qid && in_array($dec,['승인','거절'])) {
            $db->prepare("UPDATE report_delete_request SET status=?,reviewed_by=?,resolved_at=NOW() WHERE req_id=?")->execute([$dec,$uid,$qid]);
            if ($dec==='승인') {
                $rs=$db->prepare("SELECT report_id FROM report_delete_request WHERE req_id=?"); $rs->execute([$qid]); $rid=$rs->fetchColumn();
                if ($rid) { $ss=$db->prepare("SELECT sale_id FROM sales_report WHERE report_id=?"); $ss->execute([$rid]); $sid=$ss->fetchColumn();
                    if($sid)$db->prepare("DELETE FROM sales WHERE sale_id=?")->execute([$sid]);
                    try{$db->prepare("UPDATE company_db SET is_active=0 WHERE source_report_id=?")->execute([$rid]);}catch(Exception $e){}
                    $db->prepare("DELETE FROM sales_report WHERE report_id=?")->execute([$rid]); writeAudit($db,'sales_report',$rid,'DELETE',[]);
                } $msg='삭제 승인 완료';
            } else {$msg='삭제 거절';}
        } header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    // ── 통화 녹음 파일 추가 업로드 ──
    if ($_POST['action']==='upload_call_file') {
        $rid=(int)($_POST['report_id']??0);
        if ($rid && !empty($_FILES['call_files']['name'][0])) {
            $uploadDir = __DIR__ . '/../uploads/call_records/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            $allowed = ['mp3','wav','ogg','m4a','aac','wma','flac','webm','mp4','3gp','amr'];
            $insF = $db->prepare("INSERT INTO report_call_files (report_id,staff_id,file_path,original_name,file_size) VALUES(?,?,?,?,?)");
            $cnt=0;
            foreach ($_FILES['call_files']['name'] as $fi => $fname_orig) {
                if ($_FILES['call_files']['error'][$fi] !== UPLOAD_ERR_OK) continue;
                $ext = strtolower(pathinfo($fname_orig, PATHINFO_EXTENSION));
                $fsize = $_FILES['call_files']['size'][$fi];
                if (!in_array($ext, $allowed) || $fsize > 50*1024*1024) continue;
                $fname = date('Ymd_His').'_'.$uid.'_'.bin2hex(random_bytes(4)).'.'.$ext;
                if (move_uploaded_file($_FILES['call_files']['tmp_name'][$fi], $uploadDir.$fname)) {
                    $insF->execute([$rid, $uid, 'uploads/call_records/'.$fname, $fname_orig, $fsize]);
                    $cnt++;
                }
            }
            $msg=$cnt.'개 녹음 파일이 업로드되었습니다.';
        }
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    if ($_POST['action']==='delete_call_file') {
        $fid=(int)($_POST['file_id']??0);
        if ($fid) {
            $old=$db->prepare("SELECT file_path,staff_id FROM report_call_files WHERE file_id=?"); $old->execute([$fid]); $f=$old->fetch();
            if ($f && ($f['staff_id']==$uid || $adm)) {
                if (file_exists(__DIR__.'/../'.$f['file_path'])) @unlink(__DIR__.'/../'.$f['file_path']);
                $db->prepare("DELETE FROM report_call_files WHERE file_id=?")->execute([$fid]);
                $msg='녹음 파일이 삭제되었습니다.';
            }
        }
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
    // ── 처리내역(댓글) 관리 ──
    if ($_POST['action']==='add_comment') {
        $saleId=(int)($_POST['sale_id']??0); $content=trim($_POST['content']??'');
        if($saleId && $content){$db->prepare("INSERT INTO sale_comments (sale_id,staff_id,content) VALUES(?,?,?)")->execute([$saleId,$uid,$content]); $msg='처리내역이 등록되었습니다.';}
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); 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]); $o=$own->fetchColumn();
            if($o==$uid||$adm){$db->prepare("UPDATE sale_comments SET content=? WHERE comment_id=?")->execute([$content,$cid]); $msg='처리내역이 수정되었습니다.';}}
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); 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]); $o=$own->fetchColumn();
            if($o==$uid||$adm){$db->prepare("DELETE FROM sale_comments WHERE comment_id=?")->execute([$cid]); $msg='처리내역이 삭제되었습니다.';}}
        header("Location: ".BASE_URL."pages/sales_report.php?msg=".urlencode($msg)); exit;
    }
}

require_once __DIR__.'/../includes/header.php';
$user=currentUser(); $user_role=$user['role']; $user_staff_id=$user['staff_id'];
$isAdmin=in_array($user_role,['ceo','sysadmin','manager']); $message=$_GET['msg']??'';
$fKey=trim($_GET['q']??''); $fStaff=$_GET['staff_id']??''; $fYear=$_GET['year']??date('Y'); $fMonth=$_GET['month']??'';
$fIndustry=$_GET['industry']??''; $fRoute=$_GET['route']??''; $fProgram=$_GET['program']??''; $fStage=$_GET['stage']??''; $fConfirm=$_GET['confirm']??'';
$fCheckDate=$_GET['check_date']??''; $fHandler=$_GET['handler']??'';
// 처리자 목록 (관리자/대표/시스템관리자)
$handlerListRpt = $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();
$years=[]; try{$years=$db->query("SELECT DISTINCT YEAR(created_at) FROM sales_report ORDER BY 1 DESC")->fetchAll(PDO::FETCH_COLUMN);}catch(Exception $e){} if(!$years)$years=[date('Y')];
$staffList=[]; $showFullFilter=in_array($user_role,['team_leader','manager','ceo','sysadmin']); if($showFullFilter)$staffList=$db->query("SELECT s2.staff_id, s2.name FROM staff s2 LEFT JOIN user_account ua2 ON s2.staff_id=ua2.staff_id WHERE s2.is_active=1 AND (ua2.user_role IS NULL OR ua2.user_role NOT IN('ceo','sysadmin','manager')) ORDER BY s2.name")->fetchAll();
/* 필터 옵션 목록 */
$industryList=[]; try{$industryList=$db->query("SELECT DISTINCT CONCAT_WS(' / ',NULLIF(sr.industry,''),NULLIF(sr.field,'')) AS v FROM sales_report sr WHERE CONCAT(sr.industry,sr.field)!='' ORDER BY v")->fetchAll(PDO::FETCH_COLUMN); $industryList=array_filter($industryList);}catch(Exception $e){}
$routeList=[]; try{$routeList=$db->query("SELECT DISTINCT contact_route FROM sales_report WHERE contact_route!='' ORDER BY contact_route")->fetchAll(PDO::FETCH_COLUMN);}catch(Exception $e){}
$programList=[]; try{$programList=$db->query("SELECT DISTINCT sl.program_name FROM sales_report sr LEFT JOIN sales sl ON sr.sale_id=sl.sale_id WHERE sl.program_name IS NOT NULL AND sl.program_name!='' ORDER BY sl.program_name")->fetchAll(PDO::FETCH_COLUMN);}catch(Exception $e){}

$sql="SELECT sr.*,s.name AS staff_name,sl.stage AS sale_stage,sl.confirm_type AS sale_confirm,sl.sale_id AS linked_sale_id,sl.program_name,sl.episode,sl.contract_date,sl.revenue,sl.cost,sl.net_profit FROM sales_report sr LEFT JOIN staff s ON sr.staff_id=s.staff_id LEFT JOIN sales sl ON sr.sale_id=sl.sale_id WHERE YEAR(sr.created_at)=?";
$params=[$fYear];
if($fMonth){$sql.=" AND MONTH(sr.created_at)=?";$params[]=(int)$fMonth;}
if($fKey){$sql.=" AND (sr.company_name LIKE ? OR sr.ceo_name LIKE ? OR sr.contact_name LIKE ? OR sr.contact_phone LIKE ? OR sr.industry LIKE ? OR sr.field LIKE ? OR sr.phone LIKE ? OR sr.mobile LIKE ? OR sr.email LIKE ? OR sr.website LIKE ? OR sr.contact_route LIKE ? OR sr.call_notes LIKE ? OR s.name LIKE ? OR sl.program_name LIKE ? OR sl.episode LIKE ?)";$kw="%{$fKey}%";$params=array_merge($params,[$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw,$kw]);}
if($fStaff){$sql.=" AND sr.staff_id=?";$params[]=(int)$fStaff;}
if($fIndustry){$sql.=" AND CONCAT_WS(' / ',NULLIF(sr.industry,''),NULLIF(sr.field,''))=?";$params[]=$fIndustry;}
if($fRoute){$sql.=" AND sr.contact_route=?";$params[]=$fRoute;}
if($fProgram){$sql.=" AND sl.program_name=?";$params[]=$fProgram;}
if($fStage){$sql.=" AND sl.stage=?";$params[]=$fStage;}
if($fConfirm){$sql.=" AND sl.confirm_type=?";$params[]=$fConfirm;}
if($fCheckDate){$sql.=" AND sr.check_date=?";$params[]=$fCheckDate;}
if($fHandler){$sql.=" AND sr.handler_name=?";$params[]=$fHandler;}
if(!$isAdmin){$sql.=" AND sr.staff_id=?";$params[]=$user_staff_id;}
$sql.=" ORDER BY CASE WHEN sl.confirm_type='확정' THEN 0 ELSE 1 END ASC, sr.check_date DESC, sr.created_at DESC";
$stmt=$db->prepare($sql); $stmt->execute($params); $allR=$stmt->fetchAll();
$commentMap=[];
try{$sids=array_filter(array_column($allR,'linked_sale_id'));
if($sids){$in=implode(',',array_fill(0,count($sids),'?'));$cm=$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($in) ORDER BY sc.created_at ASC");$cm->execute($sids);foreach($cm->fetchAll() as $c)$commentMap[$c['sale_id']][]=$c;}}catch(Exception $e){}
$callFileMap=[];
try{$rids=array_filter(array_column($allR,'report_id'));
if($rids){$in2=implode(',',array_fill(0,count($rids),'?'));$cf=$db->prepare("SELECT * FROM report_call_files WHERE report_id IN($in2) ORDER BY created_at ASC");$cf->execute($rids);foreach($cf->fetchAll() as $f)$callFileMap[$f['report_id']][]=$f;}}catch(Exception $e){}
$totalCnt=count($allR); $perPage=10; $page=max(1,(int)($_GET['page']??1)); $totalPages=max(1,ceil($totalCnt/$perPage)); $reports=array_slice($allR,($page-1)*$perPage,$perPage);
?>
<div class="page-header"><h2>📝 실적 보고서</h2></div>
<?php if($message):?><div class="alert alert-success">✓ <?=htmlspecialchars($message)?></div><?php endif;?>
<div class="card" style="margin-bottom:1rem;padding:0.85rem 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($years as $y):?><option value="<?=$y?>" <?=$fYear==$y?'selected':''?>><?=$y?>년</option><?php endforeach;?></select>
    <select name="month" onchange="this.form.submit()" class="dash-filter" style="width:7rem;"><option value="">월 전체</option><?php for($m=1;$m<=12;$m++):?><option value="<?=$m?>" <?=$fMonth==$m?'selected':''?>><?=$m?>월</option><?php endfor;?></select>
    <?php if($showFullFilter):?><select name="staff_id" onchange="this.form.submit()" class="dash-filter" style="width:9rem;"><option value="">담당자 전체</option><?php foreach($staffList as $s):?><option value="<?=$s['staff_id']?>" <?=$fStaff==$s['staff_id']?'selected':''?>><?=htmlspecialchars($s['name'])?></option><?php endforeach;?></select><?php endif;?>
    <select name="industry" onchange="this.form.submit()" class="dash-filter" style="width:9rem;"><option value="">업종/분야 전체</option><?php foreach($industryList as $iv):?><option value="<?=htmlspecialchars($iv)?>" <?=$fIndustry===$iv?'selected':''?>><?=htmlspecialchars($iv)?></option><?php endforeach;?></select>
    <select name="route" onchange="this.form.submit()" class="dash-filter" style="width:9rem;"><option value="">컨택경로 전체</option><?php foreach($routeList as $rv):?><option value="<?=htmlspecialchars($rv)?>" <?=$fRoute===$rv?'selected':''?>><?=htmlspecialchars($rv)?></option><?php endforeach;?></select>
    <select name="program" onchange="this.form.submit()" class="dash-filter" style="width:9rem;"><option value="">프로그램 전체</option><?php foreach($programList as $pv):?><option value="<?=htmlspecialchars($pv)?>" <?=$fProgram===$pv?'selected':''?>><?=htmlspecialchars($pv)?></option><?php endforeach;?></select>
    <select name="stage" onchange="this.form.submit()" class="dash-filter" style="width:7rem;"><option value="">단계 전체</option><?php foreach(['미진행','리드','제안','계약','촬영','방송완료'] as $sv):?><option value="<?=$sv?>" <?=$fStage===$sv?'selected':''?>><?=$sv?></option><?php endforeach;?></select>
    <select name="confirm" onchange="this.form.submit()" class="dash-filter" style="width:8rem;"><option value="">확정/예상 전체</option><option value="확정" <?=$fConfirm==='확정'?'selected':''?>>확정</option><option value="예상" <?=$fConfirm==='예상'?'selected':''?>>예상</option></select>
    <select name="handler" onchange="this.form.submit()" class="dash-filter" style="width:8rem;"><option value="">처리자 전체</option><?php foreach($handlerListRpt as $hl):?><option value="<?=htmlspecialchars($hl['name'])?>" <?=$fHandler===$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($fCheckDate)?>" onchange="this.form.submit()" class="dash-filter" style="width:100%;<?=$fCheckDate?'':'color:transparent;'?>" onfocus="this.style.color=''" onchange="this.style.color='';this.form.submit()" onblur="if(!this.value)this.style.color='transparent'"><?php if(!$fCheckDate):?><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>
    <div style="flex:1;"></div>
    <?php if($showFullFilter):?>
    <input type="text" name="q" value="<?=htmlspecialchars($fKey)?>" placeholder="검색어를 입력하세요." class="report-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>
    <?php endif;?>
    <button type="button" class="btn btn-primary" style="padding:0.45rem 0.9rem;font-size:14px;" onclick="document.getElementById('createModal').classList.add('show')">📝 보고서 등록</button>
</form></div>

<div class="card"><div class="card-header"><h3>보고서 목록 (<?=$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><th>순이익</th><th>단계</th><th>확정/예상</th><th>진행확인일</th><th>처리자</th><th>처리내역</th><th>통화내용</th><th>녹취</th><th>관리</th></tr></thead><tbody>
<?php foreach($reports as $i=>$r): $cmts=$commentMap[$r['linked_sale_id']??0]??[];?>
<tr>
<td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?=$totalCnt-(($page-1)*$perPage)-$i?></td>
<td style="font-size:var(--fs-xs);white-space:nowrap;"><?=date('Y-m-d',strtotime($r['created_at']))?></td>
<td><strong><?=htmlspecialchars($r['staff_name']??'')?></strong></td>
<td><strong style="color:var(--accent-text);"><?=htmlspecialchars($r['company_name'])?></strong></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['ceo_name'])?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['phone']??'')?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['contact_name']??'')?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['contact_phone']??'')?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['industry'])?><?=$r['field']?' / '.htmlspecialchars($r['field']):''?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['contact_route'])?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['program_name']??'')?></td>
<td style="font-size:var(--fs-xs);"><?=htmlspecialchars($r['episode']??'')?></td>
<td style="font-size:var(--fs-xs);white-space:nowrap;"><?=$r['contract_date']??'-'?></td>
<td style="font-size:var(--fs-xs);text-align:right;" class="font-mono"><?=$r['revenue']?number_format($r['revenue']):'-'?></td>
<td style="font-size:var(--fs-xs);text-align:right;" class="font-mono"><?=$r['cost']?number_format($r['cost']):'-'?></td>
<td style="font-size:var(--fs-xs);text-align:right;font-weight:600;" class="font-mono"><?=$r['net_profit']?number_format($r['net_profit']):'-'?></td>
<td><?php $stg=$r['sale_stage']?:'미진행';?><span class="badge stage-<?=$stg?>"><?=$stg?></span></td>
<td><?php if($r['sale_confirm']):?><?=$r['sale_confirm']==='확정'?'<span class="badge badge-success">확정</span>':'<span class="badge badge-gray">예상</span>'?><?php else:?><span style="color:var(--text-tertiary);font-size:var(--fs-xs);">-</span><?php endif;?></td>
<td style="font-size:var(--fs-xs);white-space:nowrap;"><?=$r['check_date']??'-'?></td>
<td style="font-size:var(--fs-xs);white-space:nowrap;"><?php $hn=$r['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="font-size:var(--fs-xs);white-space:nowrap;"><?php if($cmts):?><span style="cursor:pointer;color:#FFD54F;font-weight:500;" onclick="openCmtView(<?=htmlspecialchars(json_encode($cmts,JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE))?>,'<?=htmlspecialchars($r['company_name'],ENT_QUOTES)?>',<?=(int)($r['linked_sale_id']??0)?>)">💬 <?=count($cmts)?>건</span><?php else:?><span style="color:#90A4AE;font-weight:500;">💬 0</span><?php endif;?>
    <button onclick="openCmtView(<?=htmlspecialchars(json_encode($cmts,JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE))?>,'<?=htmlspecialchars($r['company_name'],ENT_QUOTES)?>',<?=(int)($r['linked_sale_id']??0)?>)" 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);max-width:10rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?=htmlspecialchars($r['call_notes']??'')?>"><?=htmlspecialchars(mb_substr($r['call_notes']??'',0,25))?><?=mb_strlen($r['call_notes']??'')>25?'...':''?></td>
<td style="font-size:var(--fs-xs);white-space:nowrap;text-align:center;"><?php $cfiles=$callFileMap[$r['report_id']]??[]; if($cfiles):?><span style="cursor:pointer;color:#4FC3F7;font-weight:500;" onclick="openCallFiles(<?=$r['report_id']?>,'<?=htmlspecialchars($r['company_name'],ENT_QUOTES)?>')">🎙️ <?=count($cfiles)?>건</span><?php else:?><span style="color:#90A4AE;">🎙️ 0</span><?php endif;?></td>
<td style="white-space:nowrap;">
    <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;" onclick='openView(<?=json_encode($r,JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE)?>)'>📋</button>
    <button class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);padding:0.15rem 0.4rem;" onclick='openEdReq(<?=json_encode($r,JSON_HEX_APOS|JSON_HEX_QUOT|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='openDelReq(<?=$r["report_id"]?>,"<?=htmlspecialchars($r["company_name"],ENT_QUOTES)?>")'>🗑️</button>
</td></tr>
<?php endforeach; if(empty($reports)):?><tr><td colspan="24" style="padding:2rem;color:var(--text-tertiary);">보고서가 없습니다.</td></tr><?php endif;?>
</tbody></table></div>
<?php if($totalPages>1):?><div style="display:flex;justify-content:center;gap:0.5rem;padding:1rem;align-items:center;">
<span style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 <?=$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;
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;
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($isAdmin):
$pedit=$pdel=[];
try{$pedit=$db->query("SELECT r.*,sr.company_name AS orig_company,s.name AS rname FROM report_edit_request r LEFT JOIN sales_report sr ON r.report_id=sr.report_id LEFT JOIN staff s ON r.requested_by=s.staff_id WHERE r.status='대기' ORDER BY r.created_at DESC")->fetchAll();}catch(Exception $e){}
try{$pdel=$db->query("SELECT r.*,sr.company_name,s.name AS rname FROM report_delete_request r LEFT JOIN sales_report sr ON r.report_id=sr.report_id LEFT JOIN staff s ON r.requested_by=s.staff_id WHERE r.status='대기' ORDER BY r.created_at DESC")->fetchAll();}catch(Exception $e){}
if($pedit):?><div class="card" style="margin-top:1.25rem;"><div class="card-header"><h3>✏️ 수정 요청 (<?=count($pedit)?>건)</h3></div><div class="table-wrap"><table><thead><tr><th>요청자</th><th>업체명</th><th>사유</th><th>요청일</th><th>처리</th></tr></thead><tbody>
<?php foreach($pedit as $pe):?><tr><td><strong><?=htmlspecialchars($pe['rname']??'-')?></strong></td><td><?=htmlspecialchars($pe['orig_company']??'-')?></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></div><?php endif;
if($pdel):?><div class="card" style="margin-top:1.25rem;"><div class="card-header"><h3>🗑️ 삭제 요청 (<?=count($pdel)?>건)</h3></div><div class="table-wrap"><table><thead><tr><th>요청자</th><th>업체명</th><th>사유</th><th>요청일</th><th>처리</th></tr></thead><tbody>
<?php foreach($pdel as $pd):?><tr><td><strong><?=htmlspecialchars($pd['rname']??'-')?></strong></td><td><?=htmlspecialchars($pd['company_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></div><?php endif; endif;?>

<!-- 녹취 파일 리스트 모달 -->
<div class="modal-overlay" id="callFilesModal"><div class="modal" style="max-width:520px;"><div class="modal-header"><h3>🎙️ 녹취 파일</h3><button class="modal-close" onclick="document.getElementById('callFilesModal').classList.remove('show')">&times;</button></div>
<div id="cfCompanyName" style="font-size:14px;color:var(--text-tertiary);margin-bottom:0.75rem;"></div>
<div id="cfFileList" style="max-height:400px;overflow-y:auto;"></div>
<div style="text-align:center;margin-top:0.75rem;"><button class="btn btn-outline" onclick="document.getElementById('callFilesModal').classList.remove('show')">닫기</button></div>
</div></div>

<!-- 등록 모달 -->
<div class="modal-overlay" id="createModal"><div class="modal" style="max-width:600px;"><div class="modal-header"><h3>📝 보고서 등록</h3><button class="modal-close" onclick="document.getElementById('createModal').classList.remove('show')">&times;</button></div>
<form method="POST" enctype="multipart/form-data" onkeydown="if(event.key==='Enter'&&event.target.tagName!=='TEXTAREA'){event.preventDefault();}"><input type="hidden" name="action" value="create_report">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><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 style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><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 style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><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 style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><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 style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><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://"></div></div>
<div class="form-group"><label>컨택경로</label><input type="text" name="contact_route" placeholder="지인 소개, 전화 영업 등"></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>진행 확인일</label><input type="date" name="check_date"></div><div class="form-group"><label>단계 <span class="required">*</span></label><select name="stage" required style="width:100%;"><option value="" disabled selected>단계 선택</option><option value="미진행">미진행</option><option value="리드">리드</option><option value="제안">제안</option><option value="계약">계약</option><option value="촬영">촬영</option><option value="방송완료">방송완료</option></select></div></div>
<div class="form-group"><label>통화 내용</label><textarea name="call_notes" rows="1" placeholder="통화 내용 메모" class="ta-auto" style="resize:none;min-height:2.2rem;line-height:1.5;"></textarea></div>
<div class="form-group"><label>🎙️ 통화 녹음 파일</label>
<input type="file" name="call_files[]" multiple accept=".mp3,.wav,.ogg,.m4a,.aac,.wma,.flac,.webm,.mp4,.3gp,.amr" style="font-size:14px;padding:0.4rem;background:rgba(255,255,255,0.04);border:1px dashed rgba(255,255,255,0.15);border-radius:var(--radius-xs);width:100%;color:var(--text-secondary);cursor:pointer;">
<div style="font-size:14px;color:var(--text-tertiary);margin-top:0.25rem;">mp3, wav, ogg, m4a, aac 등 · 최대 50MB · 여러 파일 선택 가능</div>
</div>
<button type="submit" class="btn btn-success" style="width:100%;">등록</button></form></div></div>

<!-- 보기 모달 -->
<div class="modal-overlay" id="viewModal"><div class="modal" style="max-width:560px;"><div class="modal-header"><h3>📋 보고서 상세</h3><button class="modal-close" onclick="document.getElementById('viewModal').classList.remove('show')">&times;</button></div>
<div 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:80px;flex-shrink:0;color:var(--text-tertiary);">업체명</span><span style="font-weight:600;" id="v_cn"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">대표자</span><span id="v_ceo"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">담당자명</span><span id="v_ctname"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">담당자번호</span><span id="v_ctphone"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">업종</span><span id="v_ind"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">분야</span><span id="v_fld"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">대표전화</span><span id="v_ph"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">휴대폰</span><span id="v_mb"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">메일</span><span id="v_em"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">홈페이지</span><span id="v_web"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">컨택경로</span><span id="v_rt"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">진행확인일</span><span id="v_chk"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">단계</span><span id="v_stage"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">처리자</span><span id="v_handler"></span></div>
<div style="display:flex;padding:0.4rem 0;border-bottom:1px solid rgba(255,255,255,0.05);"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">통화내용</span><span style="white-space:pre-wrap;" id="v_nt"></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:80px;flex-shrink:0;color:var(--text-tertiary);padding-top:0.2rem;">녹음파일</span><div id="v_audio_wrap" style="flex:1;"></div></div>
</div>
<div style="display:flex;padding:0.4rem 0;"><span style="width:80px;flex-shrink:0;color:var(--text-tertiary);">담당자</span><span style="color:var(--accent);font-weight:600;" id="v_st"></span></div>
</div>
<div style="text-align:center;margin-top:0.75rem;"><button class="btn btn-outline" onclick="document.getElementById('viewModal').classList.remove('show')">닫기</button></div></div></div>

<!-- 수정 요청 모달 -->
<div class="modal-overlay" id="editReqModal"><div class="modal" style="max-width:600px;"><div class="modal-header"><h3>✏️ 수정 요청</h3><button class="modal-close" onclick="document.getElementById('editReqModal').classList.remove('show')">&times;</button></div>
<form method="POST" onkeydown="if(event.key==='Enter'&&event.target.tagName!=='TEXTAREA'){event.preventDefault();}"><input type="hidden" name="action" value="request_edit"><input type="hidden" name="report_id" id="ed_rid">
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>업체명</label><input type="text" name="company_name" id="ed_cn"></div><div class="form-group"><label>대표자명</label><input type="text" name="ceo_name" id="ed_ceo"></div></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>담당자명</label><input type="text" name="contact_name" id="ed_ctname"></div><div class="form-group"><label>담당자 번호</label><input type="text" name="contact_phone" id="ed_ctphone"></div></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>업종</label><input type="text" name="industry" id="ed_ind"></div><div class="form-group"><label>분야</label><input type="text" name="field" id="ed_fld"></div></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>대표전화</label><input type="text" name="phone" id="ed_ph"></div><div class="form-group"><label>휴대폰</label><input type="text" name="mobile" id="ed_mb"></div></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>메일</label><input type="email" name="email" id="ed_em"></div><div class="form-group"><label>홈페이지</label><input type="url" name="website" id="ed_web"></div></div>
<div class="form-group"><label>컨택경로</label><input type="text" name="contact_route" id="ed_rt"></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>진행 확인일</label><input type="date" name="check_date" id="ed_chk"></div><div class="form-group"><label>단계</label><select name="stage" id="ed_stage" style="width:100%;"><option value="미진행">미진행</option><option value="리드">리드</option><option value="제안">제안</option><option value="계약">계약</option><option value="촬영">촬영</option><option value="방송완료">방송완료</option></select></div></div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;"><div class="form-group"><label>처리자</label><input type="text" id="ed_handler" readonly style="background:rgba(255,255,255,0.03);color:var(--text-tertiary);" placeholder="실적 검토에서 지정"></div><div class="form-group"></div></div>
<div class="form-group"><label>통화 내용</label><textarea name="call_notes" id="ed_nt" rows="1" class="ta-auto" style="resize:none;min-height:2.2rem;line-height:1.5;"></textarea></div>
<div class="form-group"><label>🎙️ 통화 녹음</label>
<div id="ed_audio_area"></div>
</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>
<button type="submit" class="btn btn-primary" style="width:100%;">수정 요청</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="report_id" id="del_rid">
<div style="margin-bottom:0.75rem;font-size:var(--fs-sm);"><strong id="del_cn"></strong> 보고서 삭제 요청</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);">승인 시 연결된 실적·기업DB도 함께 처리됩니다.</div>
<button type="submit" class="btn btn-primary" style="width:100%;">삭제 요청</button></form></div></div>

<!-- 처리내역 관리 (실적 검토 동일) -->
<div class="modal-overlay" id="cmtModal"><div class="modal" style="max-width:560px;"><div class="modal-header"><h3>📋 관리 - 처리내역</h3><button class="modal-close" onclick="document.getElementById('cmtModal').classList.remove('show')">&times;</button></div>
<div id="cmtCompanyInfo" style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-bottom:0.75rem;font-weight:600;"></div>
<div id="cmtBody" 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="cmt_sale_id">
    <div style="flex:1;"><textarea name="content" id="cmt_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:14px;white-space:nowrap;">등록</button>
</form>
</div></div>

<script>
document.addEventListener('DOMContentLoaded',function(){
    function autoResize(ta){ta.style.height='1px';ta.style.height=Math.max(ta.scrollHeight,35)+'px';}
    document.addEventListener('input',function(e){if(e.target.classList.contains('ta-auto'))autoResize(e.target);},false);
    document.addEventListener('paste',function(e){if(e.target.classList.contains('ta-auto'))setTimeout(function(){autoResize(e.target);},0);},false);
    window._autoResize=autoResize;
});
var _callFileMap = <?= json_encode($callFileMap, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>;

function openCallFiles(reportId, companyName) {
    document.getElementById('cfCompanyName').textContent = companyName;
    var files = _callFileMap[reportId] || [];
    var baseUrl = '<?=BASE_URL?>';
    var canManage = <?= $isAdmin?'true':'false' ?>;
    var myStaffId = <?= $user['staff_id'] ?>;
    var el = document.getElementById('cfFileList');
    var h = '';
    if (!files.length) {
        h += '<div style="color:var(--text-tertiary);font-size:14px;padding:1rem;text-align:center;">녹취 파일이 없습니다.</div>';
    } else {
        files.forEach(function(cf, idx) {
            var dt = cf.created_at ? cf.created_at.substring(0, 10) : '';
            var origName = cf.original_name || ('녹취_' + (idx+1));
            var showDel = canManage || cf.staff_id == myStaffId;
            h += '<div style="padding:0.6rem 0.7rem;margin-bottom:0.5rem;background:rgba(255,255,255,0.03);border-radius:8px;border-left:3px solid #4FC3F7;">';
            h += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.35rem;">';
            h += '<span style="font-size:14px;color:var(--text-secondary);font-weight:600;">' + dt + '</span>';
            h += '<div style="display:flex;gap:0.5rem;align-items:center;">';
            h += '<a href="' + baseUrl + cf.file_path + '" download style="font-size:14px;color:var(--accent);text-decoration:none;">📥 다운로드</a>';
            if(showDel){
                h += '<form method="POST" style="display:inline;margin:0;" onsubmit="return confirm(\'이 녹음 파일을 삭제하시겠습니까?\')"><input type="hidden" name="action" value="delete_call_file"><input type="hidden" name="file_id" value="'+cf.file_id+'"><button type="submit" style="background:none;border:none;color:#ff6b6b;cursor:pointer;font-size:14px;padding:0;" title="삭제">🗑️</button></form>';
            }
            h += '</div></div>';
            h += '<audio controls preload="metadata" style="width:100%;height:2.2rem;"><source src="' + baseUrl + cf.file_path + '"></audio>';
            h += '<div style="font-size:14px;color:var(--text-tertiary);margin-top:0.2rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + origName + '">' + origName + '</div>';
            h += '</div>';
        });
    }
    /* 추가 업로드 */
    h += '<div style="margin-top:0.5rem;padding-top:0.5rem;border-top:1px solid rgba(255,255,255,0.06);">';
    h += '<form method="POST" enctype="multipart/form-data" style="display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap;">';
    h += '<input type="hidden" name="action" value="upload_call_file"><input type="hidden" name="report_id" value="'+reportId+'">';
    h += '<input type="file" name="call_files[]" multiple accept=".mp3,.wav,.ogg,.m4a,.aac,.wma,.flac,.webm,.mp4,.3gp,.amr" style="font-size:14px;flex:1;min-width:180px;color:var(--text-secondary);cursor:pointer;">';
    h += '<button type="submit" class="btn btn-sm btn-primary" style="font-size:14px;padding:0.25rem 0.6rem;">추가 업로드</button>';
    h += '</form>';
    h += '<div style="font-size:14px;color:var(--text-tertiary);margin-top:0.25rem;">여러 파일 선택 가능 · 최대 50MB/파일</div>';
    h += '</div>';
    el.innerHTML = h;
    document.getElementById('callFilesModal').classList.add('show');
}

function openView(r){
    var f={'v_cn':'company_name','v_ceo':'ceo_name','v_ctname':'contact_name','v_ctphone':'contact_phone','v_ind':'industry','v_fld':'field','v_ph':'phone','v_mb':'mobile','v_em':'email','v_web':'website','v_rt':'contact_route','v_nt':'call_notes','v_st':'staff_name','v_chk':'check_date','v_handler':'handler_name','v_stage':'sale_stage'};
    for(var k in f){
        if(k==='v_stage'){
            var stg=r[f[k]]||'미진행';
            document.getElementById(k).innerHTML='<span class="badge stage-'+stg+'">'+stg+'</span>';
        } else {
            document.getElementById(k).textContent=r[f[k]]||'-';
        }
    }
    /* 녹음 파일 목록 (듣기/다운로드만) */
    var aw=document.getElementById('v_audio_wrap');
    var files=_callFileMap[r.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.4rem;padding:0.35rem 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('viewModal').classList.add('show');
}
function openEdReq(r){
    document.getElementById('ed_rid').value=r.report_id;
    document.getElementById('ed_cn').value=r.company_name||'';
    document.getElementById('ed_ceo').value=r.ceo_name||'';
    document.getElementById('ed_ctname').value=r.contact_name||'';
    document.getElementById('ed_ctphone').value=r.contact_phone||'';
    document.getElementById('ed_ind').value=r.industry||'';
    document.getElementById('ed_fld').value=r.field||'';
    document.getElementById('ed_ph').value=r.phone||'';
    document.getElementById('ed_mb').value=r.mobile||'';
    document.getElementById('ed_em').value=r.email||'';
    document.getElementById('ed_web').value=r.website||'';
    document.getElementById('ed_rt').value=r.contact_route||'';
    document.getElementById('ed_chk').value=r.check_date||'';
    document.getElementById('ed_handler').value=r.handler_name||'';
    document.getElementById('ed_stage').value=r.sale_stage||'미진행';
    var ta=document.getElementById('ed_nt');ta.value=r.call_notes||'';
    /* 녹음 파일 영역 (읽기 전용 — 중첩 form 방지) */
    var area=document.getElementById('ed_audio_area');
    var baseUrl='<?=BASE_URL?>';
    var files=_callFileMap[r.report_id]||[];
    var h='';
    if(files.length){
        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.4rem;padding:0.35rem 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>';
        });
    } else {
        h+='<div style="font-size:14px;color:var(--text-tertiary);">녹음 파일 없음</div>';
    }
    h+='<div style="font-size:14px;color:var(--text-tertiary);margin-top:0.3rem;">※ 녹음파일 추가/삭제는 목록의 🎙️ 버튼에서 가능합니다.</div>';
    area.innerHTML=h;
    document.getElementById('editReqModal').classList.add('show');
    setTimeout(function(){if(window._autoResize)window._autoResize(ta);},50);
}
function openDelReq(id,nm){document.getElementById('del_rid').value=id;document.getElementById('del_cn').textContent=nm;document.getElementById('delReqModal').classList.add('show');}
var _srCommentMap = <?= json_encode($commentMap, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>;
var _srUserStaffId = <?= $user['staff_id'] ?>;
var _srIsAdmin = <?= $isAdmin?'true':'false' ?>;

function autoResizeSR(el) {
    el.style.height = 'auto';
    el.style.height = Math.max(el.scrollHeight, 34) + 'px';
}
(function() {
    var ta = document.getElementById('cmt_textarea');
    if (!ta) return;
    ['input','paste','change','keydown'].forEach(function(evt) {
        ta.addEventListener(evt, function() { var self = this; setTimeout(function(){ autoResizeSR(self); }, 0); });
    });
})();

function openCmtView(cmts, cn, saleId) {
    document.getElementById('cmtCompanyInfo').textContent = cn + ' 처리내역';
    document.getElementById('cmt_sale_id').value = saleId || '';
    var ta = document.getElementById('cmt_textarea');
    if (ta) { ta.value = ''; ta.style.height = 'auto'; }
    /* saleId 없으면 입력폼 숨기기 */
    ta.closest('form').style.display = saleId ? 'flex' : 'none';
    var h = '';
    if (!cmts || !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 == _srUserStaffId || _srIsAdmin);
        h += '<div id="sr_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="srEditCmt('+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="sr_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="sr_cmt_edit_'+c.comment_id+'" style="display:none;margin:0.25rem 0;">';
        h += '<textarea id="sr_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="srSaveCmt('+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="srCancelCmt('+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('cmtBody').innerHTML = h;
    document.getElementById('cmtModal').classList.add('show');
    cmts && cmts.forEach(function(c) {
        var eta = document.getElementById('sr_cmt_ta_'+c.comment_id);
        if (eta) { ['input','paste','change','keydown'].forEach(function(evt) { eta.addEventListener(evt, function() { var self = this; setTimeout(function(){ autoResizeSR(self); }, 0); }); }); }
    });
}
function srEditCmt(cid) {
    document.getElementById('sr_cmt_view_'+cid).style.display = 'none';
    var ed = document.getElementById('sr_cmt_edit_'+cid); ed.style.display = 'block';
    var ta = document.getElementById('sr_cmt_ta_'+cid); if(ta){ autoResizeSR(ta); ta.focus(); }
}
function srCancelCmt(cid) {
    document.getElementById('sr_cmt_view_'+cid).style.display = '';
    document.getElementById('sr_cmt_edit_'+cid).style.display = 'none';
}
function srSaveCmt(cid) {
    var ta = document.getElementById('sr_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>
<style>.ta-auto{overflow:hidden !important;}.report-search::placeholder{color:var(--form-placeholder,#555560);}</style>
<?php require_once __DIR__.'/../includes/footer.php';?>
