csv_file = RAMAIS_TELEFONICOS_CSV_FILE; $this->ensure_csv_exists(); } private function ensure_csv_exists() { if (!file_exists($this->csv_file)) { wp_mkdir_p(RAMAIS_TELEFONICOS_CSV_DIR); $this->write_csv_row($this->columns); } } public function get_all_ramais() { if (!file_exists($this->csv_file)) { return array(); } $ramais = array(); $handle = fopen($this->csv_file, 'r'); if ($handle !== false) { // Pula o cabeƧalho fgetcsv($handle); while (($data = fgetcsv($handle)) !== false) { if (count($data) === count($this->columns)) { $ramais[] = array_combine($this->columns, $data); } } fclose($handle); } return $ramais; } public function get_filtered_ramais($filters = array(), $page = 1, $per_page = RAMAIS_TELEFONICOS_PER_PAGE) { $all_ramais = $this->get_all_ramais(); $filtered = array(); foreach ($all_ramais as $ramal) { $match = true; if (!empty($filters['search'])) { $search = strtolower($filters['search']); $match = false; foreach ($ramal as $value) { if (strpos(strtolower($value), $search) !== false) { $match = true; break; } } } if ($match && !empty($filters['secretaria']) && $ramal['secretaria'] !== $filters['secretaria']) { $match = false; } if ($match && !empty($filters['setor']) && $ramal['setor'] !== $filters['setor']) { $match = false; } if ($match) { $filtered[] = $ramal; } } $total = count($filtered); $total_pages = ceil($total / $per_page); $offset = ($page - 1) * $per_page; $paginated = array_slice($filtered, $offset, $per_page); return array( 'data' => $paginated, 'total' => $total, 'pages' => $total_pages, 'current_page' => $page ); } public function add_ramal($data) { $sanitized = array(); foreach ($this->columns as $col) { $sanitized[$col] = $this->sanitize_field($col, $data[$col] ?? ''); } if ($this->validate_ramal($sanitized)) { return $this->write_csv_row($sanitized); } return false; } private function sanitize_field($field, $value) { switch ($field) { case 'email': return sanitize_email($value); case 'ramal': return preg_replace('/[^0-9]/', '', $value); default: return sanitize_text_field($value); } } private function validate_ramal($data) { foreach ($data as $value) { if (empty($value)) { return false; } } return is_email($data['email']); } private function write_csv_row($data) { $handle = fopen($this->csv_file, 'a'); if ($handle === false) { return false; } $success = fputcsv($handle, $data); fclose($handle); return (bool)$success; } public function get_unique_values($field) { $ramais = $this->get_all_ramais(); $values = array_column($ramais, $field); $unique = array_unique($values); sort($unique); return $unique; } }