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

// POST: 엑셀 생성, GET?download=: 다운로드
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1) JSON 데이터 받기
    $jsonData = file_get_contents('php://input');
    $payload  = json_decode($jsonData, true);
    if (!$payload) {
        echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
        exit;
    }
    // rows 키가 있으면 그 배열, 없으면 최상위 배열로 간주
    $items = isset($payload['rows']) && is_array($payload['rows'])
           ? $payload['rows']
           : $payload;

    // 2) PHPExcel 로드
    require_once($_SERVER['DOCUMENT_ROOT'] . '/PHPExcel_1.8.0/Classes/PHPExcel.php');
    // PHPExcel_IOFactory 가 없으면 아래 라인 추가
    // require_once($_SERVER['DOCUMENT_ROOT'] . '/PHPExcel_1.8.0/Classes/PHPExcel/IOFactory.php');

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->setActiveSheetIndex(0);

    // 3) 헤더 설정
    $headers = [
      '순번','1차 면접','이름','성별','나이',
      '연락처','총 경력','거주지','희망연봉','경력사항 요약'
    ];
    $col = 'A';
    foreach ($headers as $h) {
        $cell = $col . '1';
        $sheet->setCellValue($cell, $h);
        $style = $sheet->getStyle($cell);
        $style->getFont()->setBold(true);
        $style->getFill()
              ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
              ->getStartColor()->setRGB('D9D9D9');
        $col++;
    }

    // 4) 데이터 입력
    $rowNum = 2;
    foreach ($items as $item) {
        $sheet->setCellValue("A{$rowNum}", $item['seq'] ?? '');
        $sheet->setCellValue("B{$rowNum}", $item['interview'] ?? '');
        $sheet->setCellValue("C{$rowNum}", $item['name'] ?? '');
        $sheet->setCellValue("D{$rowNum}", $item['gender'] ?? '');
        $sheet->setCellValue("E{$rowNum}", $item['age'] ?? '');
        $sheet->setCellValue("F{$rowNum}", $item['contact'] ?? '');
        $sheet->setCellValue("G{$rowNum}", $item['career'] ?? '');
        $sheet->setCellValue("H{$rowNum}", $item['residence'] ?? '');
        $sheet->setCellValue("I{$rowNum}", $item['salary'] ?? '');
        $sheet->setCellValue("J{$rowNum}", $item['summary'] ?? '');
        $rowNum++;
    }

    // 5) 열 너비 자동조정
    foreach (range('A','J') as $columnID) {
        $sheet->getColumnDimension($columnID)->setAutoSize(true);
    }

    // 6) 파일 저장 경로 준비
    $filename = 'applicants_' . date('Ymd_His') . '.xlsx';
    $dir      = $_SERVER['DOCUMENT_ROOT'] . '/excel/';
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    $filepath = $dir . $filename;

    // 7) 쓰기 및 응답
    $writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $writer->save($filepath);

    echo json_encode(['success' => true, 'filename' => $filename]);
    exit;
}
// GET 다운로드 처리
else if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['download'])) {
    $filename = basename($_GET['download']);
    $filepath = $_SERVER['DOCUMENT_ROOT'] . '/excel/' . $filename;
    if (file_exists($filepath)) {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        readfile($filepath);
        // 옵션: 다운로드 후 파일 삭제
        unlink($filepath);
        exit;
    } else {
        http_response_code(404);
        echo "File not found";
        exit;
    }
}
// 그 외
else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}
