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

$pdo = db_connect();

// DataTables에서 보낸 요청 파라미터
$draw = isset($_POST['draw']) ? intval($_POST['draw']) : 0;
$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
$length = isset($_POST['length']) ? intval($_POST['length']) : 50;
$searchValue = isset($_POST['search']['value']) ? $_POST['search']['value'] : '';

$tablename = 'phonebook';

// 전체 데이터 수 조회
$totalQuery = "SELECT COUNT(*) AS total FROM $DB.$tablename WHERE is_deleted IS NULL";
$totalStmh = $pdo->query($totalQuery);
$totalRow = $totalStmh->fetch(PDO::FETCH_ASSOC);
$totalRecords = $totalRow['total'];

// 필터링된 데이터 수 조회
$filteredQuery = "SELECT COUNT(*) AS filtered FROM $DB.$tablename WHERE is_deleted IS NULL";
if (!empty($searchValue)) {
    $filteredQuery .= " AND searchtag LIKE :search";
}
$filteredStmh = $pdo->prepare($filteredQuery);
if (!empty($searchValue)) {
    $filteredStmh->bindValue(':search', '%' . $searchValue . '%', PDO::PARAM_STR);
}
$filteredStmh->execute();
$filteredRow = $filteredStmh->fetch(PDO::FETCH_ASSOC);
$filteredRecords = $filteredRow['filtered'];

// 실제 데이터 조회
$dataQuery = "SELECT * FROM $DB.$tablename WHERE is_deleted IS NULL";
if (!empty($searchValue)) {
    $dataQuery .= " AND searchtag LIKE :search";
}
$dataQuery .= " ORDER BY num DESC LIMIT :start, :length";

$dataStmh = $pdo->prepare($dataQuery);
if (!empty($searchValue)) {
    $dataStmh->bindValue(':search', '%' . $searchValue . '%', PDO::PARAM_STR);
}
$dataStmh->bindValue(':start', $start, PDO::PARAM_INT);
$dataStmh->bindValue(':length', $length, PDO::PARAM_INT);
$dataStmh->execute();

$data = [];
while ($row = $dataStmh->fetch(PDO::FETCH_ASSOC)) {
    $data[] = [
        $row['represent'],
        $row['secondordnum'],
        $row['vendor_name'],
        $row['representative_name'],
        $row['manager_name'],
        $row['phone'],
        // 여기에 필요한 다른 열을 추가할 수 있습니다.
    ];
}

// DataTables에 반환할 데이터 형식
$response = [
    "draw" => $draw,
    "recordsTotal" => $totalRecords,
    "recordsFiltered" => $filteredRecords,
    "data" => $data
];

echo json_encode($response, JSON_UNESCAPED_UNICODE);
